ransomcloud o365: pay por your office 365 e-mail

28
1 Pay for your Office365 e-mails (and OneDrive files) Authors: Chema Alonso ([email protected]), Pablo González ([email protected]) & Ioseba Palop ([email protected]) Executive Summary Today, the world of ransomware has become a profitable business for the world of cybercrime, from which individuals and organizations are extorted in a simple but lucrative way: encrypting files by infecting the computers and then demanding money for the decryption keys. This scheme we have seen it exploited through spam campaigns, infections Exploit kits or the use of binary infected P2P networks. On the other hand, in the world of e-mail services, many organizations have begun to use public cloud schemes to offer service to this, based on popular platforms such as Microsoft Office 365 or Gmail. On these platforms, the ability to integrate related applications allows an attacker to gain access to email without obtaining the user name and password, and bypassing the 2nd Factor Authentication systems. Getting together spam attacks, with the creation of a malicious app created for Office 365 or Gmail platforms, you can build an effective ransomware specially designed for these services. In this article we explain the operation of O365 RansomCloud, a ransomware specially designed to attack Microsoft Office 365 platforms. 1.- Introduction: Spam Phishing & Spear Phishing Attacks In recent years we have seen a lot of attacks on organizations that have put an end with information theft and damage to the company reputation. Some of the cases in which security has been compromised have gained sufficient visibility in the technical community dedicated to information security to justify the need to invest in security measures and try to get more resistant to cyberattacks systems. The problem arises when trying to advance this investment in preventive rather than reactive measures only. In these cases, the effectiveness of the measures is not the optimal one and it is impossible not to go behind the attackers, leaving some fundamental challenges unresolved. RansomCloud O365

Upload: chema-alonso

Post on 13-Apr-2017

393 views

Category:

Technology


4 download

TRANSCRIPT

Page 1: RansomCloud O365: Pay por your Office 365 e-mail

1

PayforyourOffice365e-mails(andOneDrivefiles)

Authors:ChemaAlonso([email protected]),PabloGonzález([email protected])&IosebaPalop([email protected])

ExecutiveSummary

Today,theworldofransomwarehasbecomeaprofitablebusinessfortheworldofcybercrime,fromwhichindividualsandorganizationsareextortedina simplebut lucrativeway:encrypting filesby infecting the computersandthendemandingmoneyforthedecryptionkeys.Thisschemewehaveseenitexploitedthroughspamcampaigns,infectionsExploitkitsortheuseofbinaryinfectedP2Pnetworks.Ontheotherhand,intheworldofe-mailservices,many organizations have begun to use public cloud schemes toofferservicetothis,basedonpopularplatformssuchasMicrosoftOffice365 or Gmail. On these platforms, the ability to integrate relatedapplications allows an attacker to gain access to emailwithout obtainingtheusernameandpassword,andbypassingthe2ndFactorAuthenticationsystems.Getting together spam attacks,with the creation of amaliciousappcreated forOffice365orGmailplatforms,youcanbuildaneffectiveransomwarespeciallydesignedfortheseservices.InthisarticleweexplaintheoperationofO365RansomCloud,aransomwarespeciallydesignedtoattackMicrosoftOffice365platforms.

1.-Introduction:SpamPhishing&SpearPhishingAttacksIn recentyearswehaveseena lotofattacksonorganizations thathaveputanendwith informationtheftanddamagetothecompanyreputation.Someofthecases inwhichsecurityhasbeencompromisedhavegainedsufficientvisibilityinthetechnicalcommunitydedicatedto informationsecurityto justify theneedto invest insecuritymeasuresand try togetmore resistant to cyberattacks systems.Theproblemariseswhen trying toadvance this investment inpreventive rather than reactivemeasuresonly.Inthesecases,theeffectivenessofthemeasuresisnottheoptimaloneanditisimpossible not to go behind the attackers, leaving some fundamental challengesunresolved.

RansomCloud O365

Page 2: RansomCloud O365: Pay por your Office 365 e-mail

2

Ifwelookattheoriginsofmanyofthebestknownofourrecentyearsattacks,weseethat most of the attacks started with a simple Spear Phishing attack. The SpearPhishing is a scam via e-mail with the aim of obtaining unauthorized access toconfidential data or access resources. Unlike Phishing attacks, which are massivelyreleased,theSpearPhishingfocusesonaspecificorganizationorgroupofpeopleorinterest.With this typeofattack, theattackergainsaccess toan internal identityofthe organization that had set up more security measure using a username andpassword, without a second authentication factor or a second factor authorization(2FA&2FA).Aswewillseeinthisdocument,thismaystillbemuchmorecomplextoprotectwhentaking intoaccount that theattacksareaimedat theftof access email accounts, inthose scenarios where you must not compromise the username and password. Inthese scenarios, for example, theft OAuth tokens could allow an attacker to bypass2FA knowing that by its design the access via API using OAuth is out of theseprotections.Beingable toautomate this fraudulentacquisitionofOAuth tokens couldget to thepossibility to get access privileges to critical resources of the victim and implementcriticattacksonthem.Inthefollowingsectionswewilltrytoillustratethefeasibilityofthishypothesis.2.-AccountsTheftinIdPsInthisarticle,theIdP(IdentityProviders)weselectedisMicrosoft,throughitsservicesOffice 365 and Windows Live, but the work is analogous to other IdP as Twitter,Facebook,Google,andsoon.TheaimofstealingtokenstechniquesistogetaccesstoresourcesviaAPI,makingtheuser-insteadofdeliveringasetofvalidcredentials-tosubmitbyhimselfanAuthCodeOAuthwhichallowstheaccesstohisdata.IfwethinkaboutthewaysinwhichaOffice365accountcanbeprotectedagainstanattackwecanfindvariousscenarios:

- Just1FA: Inthiscase, theOffice365account isprotectedonlywithasinglefirst factor authentication (username and password). In this scenario theattackercanstealcredentialsviaSpearPhishingattacks.-2FAandApplicationPasswords:Inthiscasetheaccountisprotectedbya2FAand only those customers with application-specific password (Passwordapplication) will be exempt from passing through the 2FA. In this case, theattacker needs to deal both different scenarios: to steal the PasswordApplication of where it is stored or compromise the second factor ofauthentication- 2FAwithout Application Passwords: The account has a 2FA and no use ofApplication Passwords, so either the user, password and 2FA it is beingobtainedoranetworkattacktosessionhijackinghastobedone.

Page 3: RansomCloud O365: Pay por your Office 365 e-mail

3

-2FAwithoutanetworkor2FAaccess:Silacuentaesremota,ynohayaccesoni a la red para hacer un ataque deman in themiddle ni al 2FA, parece elentornomáscomplicado.IfwehavearemoteaccountandthereisnoAccesstothenetworksowecaninitiateamaninthemiddleor2FAattack,thentheenvironmentseemstobemorecomplicatedtohijack.

Inallthesecases,ifwefocustheeffortsonstealingOAuthtokens,allscenarioscouldbe vulnerable because none of the protective measures used apply to the attackscenarioweareabouttoexplain.3.-SpearPhishing:AttacksandcountermeasuresPhishing attacks are based on tricking the user to enter his own credentials to getinside a fake web. These sites are hosted on fraudulent domains that simulate theenvironmentknownto thevictim.So ifyouwant tostealanOffice365account,youcould simulate the login Office 365. If an Apple ID is desired to be stolen then theAppleIDwebsiteshouldbesimulated(seePicture1).Thateasy!

Picture1:APhishingwebsitestealingAppleIDdata

Inorder to attract victims to these sites, thereare two typesof attacks that canbemade.MassAttack,knownasSPAMPhishing,which isnotpersonalizedand isbeingsenttoalotofrecipientshopingforsuccessbasedonprobabilities.OrientatedAttackwhich isdirected toa specificvictim, calledSpearPhishing. In thelattercase,theemailispersonalizedwithdetailsthatcouldinducethevictimthinkthetruthfulnessofthemessage(seePicture2).ItisinthislattertypeofmessageswhereattackersputtheireffortswhenweareinastageofAPTagainstanorganization.

Page 4: RansomCloud O365: Pay por your Office 365 e-mail

4

Picture2:PersonalizedSpearPhishinge-mailorientatedtoaspecificvictim

To avoid Phishing, SPAM Phishing & Spear Phishing attacks, different security measures are to be used. There are various types of security measures and each one has to be applied to the different levels of the organization:

-Awareness:Itconsistsineducatingtheusertorecognizeoneoftheseattacks(Phishing,SPAMPhishingandSpearPhishing).Forthisreasontheyneedtobeexplainedthattheyshouldnotgivetheircredentialstoanywebsitethatsendsthemanemailaskingforit,alsotopayattentiontothedomainoftheserversthatareconnected,andsoon.Unfortunately,neithertheserecommendationsareentirelycorrectinallcases,nororganizationsencouragethemtocomply,asthemassiveandcarelessuseofbusinessemailsinsidetheorganizationgoesagainstthem.It is quite common to see teams contracted agencies hired for eventsmarketing,HRconsultingorvariousadviserstosendemailstotheemployeesof an organization requesting them to register on awebsite. This awarenessshould always be accompanied by a series of actions coherent with goodpractices that are intended to inculcate and not creating a false sense ofsecurityorconfusionamongusers.- AntiPhishingTechnology: Both in termsofemailandatbrowser level too,measures are integrated to detect SPAM Phishing emails as well as Phishingsites. Tools such as AntiPhishing filters of Google Safe Browsing orMicrosoftSmart Screen are integrated to detect sites that are doing the Phishing.However,whenwetalkabouttargetedattackssuchSpearPhishing,thethingismuchmoredifficulttodetect,andinalmostallcasesitpassesundertheradarofthesetechnologies.

Page 5: RansomCloud O365: Pay por your Office 365 e-mail

5

-SecondAuthentificationFactor:Thelastbastiontopreventtheftofaccountsistoprotectdigitalidentities.Todoso,theidealwayistoprotecttheaccountwith, at least, one extra factor of authentication. This Extra facto could besomething that may be known just for one person(password), or somethingthatonecanhaveintohispower(phoneorphysicaltoken)orsomethingthatidentifiessomebodyasaperson(biometrics).

Some organizations use smart cards protected by biometrics means or digitalcertificates stored on USB tokens that can only be opened with biometrics andpasswordsat the same time.The choicewill dependoneach system. In the caseofOffice 365 / Windows Live can put a 2FA to protect accounts. Typically, theseadditionalfactorshavetobethoughttousewhenauthenticatingadifferentchannel,a channelwhich ishas tobe completelydifferent to the first authentication factor.Thus the probability of the attack success is reduced, as if theywere to succeed inbreakingthefirstfactorwouldbenecessarytoalsosucceedinsurpassingthesecondattackidentity.

Unfortunately, none of these threemeasureswill be useful to protect users againstattacksdesignedtostealtheOAuthtokens,aswewillsee.4.-OAuthinanutshellOAuthisanauthorizationprotocolusuallyimplementedinversion2(OAuth2)inmostIdPsInternet(seePicture3).Itisbasedonalicensingsystemwheretheuserindicatesthe IdP authorizing a third party to use resources on its behalf. Thus third-partyapplicationsmayaccessdataandperformactionsonauser'sresourcesontheIdP.Tosummarizetheprocess,therearethreephases:

Picture3:OAuthoperatingdiagram

Page 6: RansomCloud O365: Pay por your Office 365 e-mail

6

4.1.-AccessrequestInthisfirstpart,anapplicationregisteredintheIdPprovidesalinktotheIdPaddresswithalistofpermissions,whichcanbecalledScopes,theapplicationidentifierandtheaddress where to return the AuthCode in case the user authorizes the use of itsresources.IncaseyouwanttoaccessOffice365,anapplicationinMicrosoftandinsidethelinktobesent to theuservictim, thedifferent fieldsdiscussedabovewillappear.Picture4and5arepresentedbelowasanexampleofaSpearPhishing.

Picture4:SPAMPhishinginafalseSpotifyaccount,leadstoahackedserver

Picture5:ThehackedserverdoesaredirecttoaURLtorequestaccesspermissions

Page 7: RansomCloud O365: Pay por your Office 365 e-mail

7

4.2.-AccessApprovalWhen the user clicks or is redirected to theURL access requested, a screen on thewebsite of IdP (Microsoft, Google, etc.) will be shown, a screen where he will beinformedoftheaccessesthatarebeingrequestedtohimandalsowhethertograntordenysuchaccess.Thatisthelastbarrierbeforegrantingtherequestingapplicationallthedataitisasking.

Picture6:TheuserisnotloggedbuttheScopeslististheURL

WhentheuserisnotloggedintheIdPservices,thewebthatappearswillbesimilartothe login (see Picture 6). However, in the URL you can see that there is a list ofpermissions that are precisely those the URL from firs point has generated. On theotherhand, iftheuserhasalreadyloggedpreviously, itwillgodirectlytothepartofgrantingordenyingtheaccesspermissions,likeonawebsiteshownbelow(seePicture7).

Picture7:SpotifyfakeapprequestingtheaccesstotheWindowsLiveaccount

Page 8: RansomCloud O365: Pay por your Office 365 e-mail

8

If theuserclicksYES, then the IdPserverwillgenerateanAuthCodeat this stagesothatwillallowtheapplicationtorequesttheaccesstokentotheresources.4.3.-AccessAchievementIf the user granted the Auth Code in the previous phase, it is now the task of theconsuming application to request the access Token. To do this you must use yourApplicationID, your Secret, your AuthCode and request that the access Token to besenttoanEndPoint.ItwillbewheretheIdPwillprovideyou,viaAPI,thevalidtokenthatgivesaccesstotherequestedresourcesintheScopeslist.Theapplicationwillberegistered in the list of apps of granted permissions. Picture 8 shows an approvedmaliciousappinaWindowsLiveaccount.

Picture8:MaliciousAppapprovingitsaccessviaWindowsLiveOAuth2

Fromnowon,theAccessviaAPIwillbepossibletoeachoftheIdPresourcesthathavebeenpreviouslygranted,aswearetoseeinthefollowingsectionsofthisarticle.5.-ConstructionoftheO365applicationRamsonCloudEntendiendo cómo funciona el sistema descrito, ya es posible trazar cómo sería unataque de este tipo. El esquema que se debe seguir consistiría en los siguientespuntos.Understandinghowthedescribedsystemworks,itispossibletotracehowanattackofthiskindcouldbe.Theschemetobefollowedconsistofthefollowingpoints.

1)BuildamaliciousapplicationfortheIdPtoattack2)BuildaURLwithanadequateSCOPEapplication(permits)3)GettingtheAuthCodewhentheuseracceptstheapp4)RequestingtheAccessTokenwiththeAuthCode5)WiththeAccessTokenaccessallservicesviaAPI6)PossibilityofusingCloudRansommoduleO365againstemailanddataoftheuservictim

Page 9: RansomCloud O365: Pay por your Office 365 e-mail

9

So far the attack vector Spear Phishing has been described, which is using Sappoplatform to carry out the theft of OAuth tokens so to access resources. The Sappoplatformprovidesdifferentmodulesthatallowtheattackertomanagethepossibilitiesonthevictim inasimpleandflexiblemanner.Oneof thefeaturesSappoprovides istheRansomCloud.TheRansomCloudallowsanattackertoencrypt,decryptandcouldaskforemailrescueofthevictim.Here is a complete example,meaning, first the theft accounts using Sappo is carriedoutandthen,runtheRansomCloudmodule.Firstlyweneedtocreateanapplication,whichwill be calledRamsonCloud, in theMicrosoftplatform tohelpusextractdatafrom the accounts that rely on it. For this purpose, using any Outlook account, wemust go to the address apps.dev.microsoft.com and create a new application (seePicture9).TherewewillreceiveanApplicationIDandaSecret,pluswehavetospecifya server with an end-point, also known as Redirect URI, where we will receive theAuthCodeandaccessToken.Thisservershouldbeinourinfrastructureandwehavetoinstallaprogramtolistenallthecalls.

Picture9:CreatingamaliciousapplicationinMicrosoft

Tocontroltheapplication,whichwehavecalledSappo,insideourdatainfrastructureweneedtoregisterthedataoftheappwehavejustcreated(seePicture10).ThiswillallowustomakeuseoftheAPIOffice365and/orWindowsLivethroughtheaccessTokengrantedtotheappbytheuserdirectlyfromourplatform.

Page 10: RansomCloud O365: Pay por your Office 365 e-mail

10

Picture10:RegisteringtheapponourplatformtolaunchRansomCloudO365

Oncewehavecreatedtheapp,wecancreatetherequestsforpermitswheretheuserhastoclicksYESandforthispurposethesocialengineeringisaveryimportantpartintheway of achieving it. In the above examplewe have called the app Sappo, so tomake clear that is this app the usermust accept, but to achieve greater impact onsocialengineeringoneshouldlookmoreattractivenames(seePicture11).

Picture11:AmaliciousAppcalledMSAntiSpamPROO365

Page 11: RansomCloud O365: Pay por your Office 365 e-mail

11

For our presentation,we have chosen to create an app that simulates to be a freeAntiSpamPro,whichdoesnotcall toomuchtheattentionwhenpermissionstoreadandwritee-mail is requested.Of course, theend-pointdomainand the logowillbeessentialtogivetheadequateeffectineachcase.6.-ConstructionoftheURLrequestScopesToobtainthenecessarypermissions,theusermustrequesttheMicrosoftserveraURLwiththefollowingformat:

GEThttps://login.microsoftonline.com/common/oauth2/authorize/common/oauth2/authorize?scope=[scope_list]&response_type=[code]&client_id=[client_id]&redirect_uri=[redirect_uri]

Asyoucansee,youneedtoidentifythattheappistheonerequestingpermission,inthiscaseClient_id,thenyouhavetospecifythe listofpermissionstobeobtained inScope_List (seePicture12) and, finally, thatwhat is expected toget is anAuthCodethatmustbedeliveredinRedirect_URI.

Picture12:SomeWindowsLiveScopes

Thelistofpermissionsthatexist inWindowsLive isa largeone(seePicture13),andalthoughsomeofthemspecifiesthatallowsreadingandwritingtheemailviaAPI,thetruth isthat inmanyoftheaccounts isnotallowedyet.Ofcourse,yforexample,toOneDrive documents, or contact list can be accessed as we will see in one of thedemos.

Page 12: RansomCloud O365: Pay por your Office 365 e-mail

12

Picture13:MoreWindowsLiveScopes.OneDriveandOneNoteAccess

In the case of Office 365, those APIs to access email are available and thereforereading,sendingemails,ordeletingmessagesfromdifferentfoldersinthemailboxofthevictimcanbedone(seePicture14).

Picture14:ScopesinOffice365

Once sent, it generates the URL, thus the next step is to have it sent to the victimthroughanemailthatwillmisleadhimtothinkitistrue.InourcasewehavechosenaMicrosoft Mail that personalizes the message and sends it as if it would be anAntiSpamPromessage.This customization we do it directly from the Sappo tool, through which you onlychooseanewvictimtowhomyousendaSappoapp(seePicture15).

Page 13: RansomCloud O365: Pay por your Office 365 e-mail

13

Picture15:SendingaSpearAPPattack

Themailsentinthisattackisgeneratedasifitwerearealmessage,sointhiswaytheuserwhoisnotespeciallyalertagainsttheseattacks,willencounterhimselfwiththediatribeofwhethertoapproveornotthepermitstothis"magnificent"appthatwillallowhimtohavelessspaminhisinbox(seePicture16).

Picture16:EmailwhichinvitesyoutoinstallMicrosoftAntiSpamProwithyourOffice365

Whenthevictimreceivestheemailandclicksonthelink,endsupwithascreenwherehisapprovalisrequested(seePicture17).

Page 14: RansomCloud O365: Pay por your Office 365 e-mail

14

Picture17:Acceptancescreenpermitsformaliciousapp

AsyoucanseeinPicture17,itisnotaPhishingwebsite.Thereisnorequestforusersandpasswords. It is under theofficial domainofMicrosoft,withHTTPsanda greencertificateasallthemeasuresfordetectingphishingattacksarebeingrecommended.Ofcourse,thebrowserphishingfilterhasnotwentoffandthevictimisa2FAaccountconfigured.Of course, on this screen it is clear that to this application, a list of permissions arebeinggranted,permissionsthatifitisamaliciousappthenitcouldbeverydangerousto accept. Unfortunately, as happens with the permissions of apps in the world ofAndroid operating systems, many users accept it without understanding the realconsequencesofit.7.-AttackingOffice365AccountsGettingtothispoint,wheretheuserhastochoosewhethertograntordenypermits,itiswhenthelatestsecuritymeasureends.Iftheuserdecidestograntthem,fromthismoment-anduntilpermitsarerevokedorexpirewithoutanyprocessofrenegotiatingtheaccessToken-theappcanaccessalltheresourceslistedintheScopeslist.When theuser clicksYES in theend-pointmarkedon theRedirect-URIanAuthCodewillbereceived,whichwillallowtheapplicationtorequesttheAccessToken.This isdonethiswaybecausetheAccessTokenrequestmustindicatetheApplicationIDandtheSecretsotoshowthattheapp’sownerhimselfneedsthepermissions.TherequesttobemadetotheAccessTokenareasfollows:

POSTcommon/oauth2/tokenHTTP/1.1Host:https://login.microsoftonline.comContent-Type:application/x-www-form-urlencodedgrant_type=[authorization_code]&code=[authCode]&client_id=[client_id]&client_secret=[secret]&redirect_uri=[redirect_uri]

Page 15: RansomCloud O365: Pay por your Office 365 e-mail

15

Asyoucansee,youareaskedtodelivertheAccessTokeninRedirect_URI,andiftheAuthCodedeliverediscorrect,theanswerthatwillgetbacktoIdPserver,inthiscaseMicrosoft,willbeanaccesstoken.7.1.-JWT(JSONWebToken)InthecaseofMicrosoft,thetokenarrivesinaJWTformatthatisnomorethanastringURL,EncodedinBASE64withathreepartsstructure:Header,PayloadandSignature.InthefollowingscreenshotyoucanseeatokenrecoveredinJWTformat(seePicture18). If we change the string in BASE64, we can see that the payload is full ofinformationabouttheentireaccesssession.Thisprovidestheappinformation,thelistofpermissionsandaccountdatathathasbeengrantedpermissionsto(seePicture19).

Picture18:Complete3partJWT

Picture19:Payloadencodedinformation

Page 16: RansomCloud O365: Pay por your Office 365 e-mail

16

This token, in a raw manner, will have to be sent in each access request to theresourcesintheIdPaccount,wheneveracalltotheAPIOffice365orWindowsLiveismade.Requestsmustbemadeintheformatbelow:

GEThttps://login.microsoftonline.com/common/oauth2/authorizeHTTP/1.1Host:login.microsoftonline.comAuthorization:Bearer[Access_Token]

Theentireprocess isautomatedonourplatform, sowhen theusergrantsaccess totheScopesofthepetition,theitemswhichwillappearonthelistoftokenswillbeallthosevalidthatcanbeusedtoaccesstheaccountdata(seePicture20).

Picture20:AvalidAccessTokentoAccessanOffice365account

7.2.-ActionsontheOffice365accountviaOAuthtokenIn the case of Office 365, the access is entirely to emails, so we can list all themessagesintheinboxorinanyotherfolderoftheaccount,or,asweshallseeinthenextsection,dotheencryptionofallmessagesandexecuteahijackingmailboxwithO365RansomCloudmodule.

Picture21:ActionsimplementedwiththisAccessTokeninsideOffice365

Page 17: RansomCloud O365: Pay por your Office 365 e-mail

17

Tomakeiteasierwehaveintegratedauserinterfacethatallowsyoutobrowseyourmailbox and launch actions. Among these options, you are also have the one ofdeletingmailmessages,theoneofsendingmessagesfromtheaccountandactivateordeactivatetheRansomCloudprocessinthisspecificmailbox(seePicture21).

Picture22:SendingemailsusingOffice365APIandtheAccessToken

Thesetypesoftechniqueshavebeenusedtocheat/misleadvictimsandstealmoneywhen a manipulated message introduced inside a legitimate conversations beingintroduced, for example, get a message that the payment of a work item to beoperated inanotherbankaccount - controlledby thecybercriminal - insteadof thevictim’saccount(seePicture22).

Picture23:Accountcontactlist

Page 18: RansomCloud O365: Pay por your Office 365 e-mail

18

Thesetasks(seePicture23)canbemadewhiletheaccesstotheOffice365applicationisnotrevoked.Toachievethis,theusershouldgotoConfigurationpartofOffice365,to the PermissionsApplication section, and remove the access to his data fromanyunwantedapp.

Picture24:Listofallemails.Canbedisplayedcompleteandwithattachments

7.3.-Office365emailhijackOnceyouhaveaccesstoallthefoldersandmessagesinamailboxfromOffice365,theprocess to hijackmailmessages is fairly straightforward. First you have to access amessage that is then downloaded to the attacker's server. After that the originalmessage is deletedwhile the attacker's server encryption itself is performed. Finallytheencryptedmessageisuploadedtotheserversotobeupthere.TheschemewouldbeassimpleasdescribedinPicture25.

Picture25:MailboxhijackprocessinOffice365

Page 19: RansomCloud O365: Pay por your Office 365 e-mail

19

Tomake thisprocessmoreeffective, theattacker couldusea systembasedon firsthijack the oldestmessages,whichwill be less possible to be accessed by the victimand, therefore, the work of mailbox hijack will have a greater opportunity timewindow/frame to encrypt the greatest possible number ofmessages.To obtain the emails in a specific folder, having the appropriate permissions on the SCOPE, the attacker only needs to use the API that provides Office 365 for it. This would be the necessary request to access e-mail messages.

POST/api/v2.0/me/messagesHTTP/1.1Host:https://outlook.office.comAuthorization:Bearer+AccessTokenX-AnchorMailBox:[email protected]:Thistokenallowaccesstoemail

Thehijackingprocessisbasedondeletingtheoriginalmessageandreplaceitwithanencrypted copy of the same. To make it more difficult to decipher by a reverseengineering algorithm, the simplest way is to use algorithms to generate randomvaluestocreateaRandomKeyandarandominitializationvector(RandomIV)foreachhijackedemailaccount.

cipher.key=aes_key=<RandomKeyforEmailAccount>cipher.iv=aes_iv=<RandomIVforEmailAccount>encrypted=cipher.update(messageBody)

With this process, the emails from the mailbox hijacked by RansomCloud will beencryptedwithAESandforthevictimwillbeuselessdocumentsthatcannotbeusedunless decrypted. This is an example (see Picture 26) of a message hijacked byRansomCloud.

Picture26:EncryptedmessageforRansomCloud

Page 20: RansomCloud O365: Pay por your Office 365 e-mail

20

The values needed to decrypt themessages are stored in a databasewhich can beaccessedfromtheplatformatanytime(seePicture27).Aseasyasyoucanhavethemessages encrypted, you candecrypt themand the system cando it autonomouslyonlybyselectingDisableRansomCloudaction.

Picture27:CipherIVandCipherKeylistofthehijackedmailboxes

Whilee-mailisencryptedontheRansomCloudserver,theoriginalmessagesmustberemovedfromtheoriginalmailbox.Todothis,theplatformwilldeletetheAPIusingOffice365offersforthesetasksandforwhichpermitswererequestedtotheScopeslistgrantedtothemaliciousappwhenthevictimaccepted.Therequestwouldbelikethis:

DELETE/api/v2.0/me/messages/{message_id}HTTP/1.1Host:https://outlook.office.comAuthorization:Bearer+AccessTokenAccessToken:ThistokenallowaccesstoemailMessage_id:Messageinthemailbox

Onceremovedtheoriginalmessage,RansomClouduploadstheencryptedmessagetothecloudusingAES,andagainthisisdonebyafunctionthatprovidestheAPIdirectly.Therequesttouploadaparticulare-mail - in thiscaseanencryptedmessagebythemaliciousapplication-isasfollows:

POST/api/v2.0/me/MailFolders/inbox/messagesHTTP/1.1Host:https://outlook.office.comContent-Type:application/json;odata.metadata=minimalAuthorization:Bearer+AccessTokenX-AnchorMailBox:[email protected]: Subject => “subject”,Message => “encryptedmessage”… toRcpt, from,etc…(Allparamsoforiginalemail)AccessToken:Thistokenallowaccesstoemail

Finally, to complete the process of hijacking the Office 365Mailbox from a victim,would be enough to give one last message, this time in clear text unencrypted, inwhich the victim is informed of what happened and how it should realize thepaymentsotoregainthecontrolofthemessagesinthemailbox.

Page 21: RansomCloud O365: Pay por your Office 365 e-mail

21

7.4.-DecryptingtheemailsThe platform, through another app accepted by the user could perform the reverse process. That is, at any time, the platform can automatically reverse the process using a model based on access messages algorithm, decrypt, delete the encrypted message mailbox and deposit the old messages unencrypted on the server (see Picture 28). The process allows the platform to manage the entire process with just one click.

Picture28:RansomCloudO365decryptedmessages

Torecoveremails,stepstobeperformedare:

cipher.key=aes_key=<RandomKeyforEmailAccount>cipher.iv=aes_iv=<RandomIVforEmailAccount>encrypted=Base64.decode64(message)decrypted=decipher.update(encrypted)+decipher.final

8.-AttackingWindowsLiveMailyOneDriveaccounts WecandoexactlythesameattackwehaveseeninthepreviouscasebutnowagainstaWindows Live account. So we could use the samemalicious app that we initiallycreated or create a different one, and also could use the same email with socialengineeringoredifferentone,butwehavetochangetheSCOPE_LISTemailrequestpermissionsotoadaptittothoseavailableinWindowsLive,whicharedifferentfromthosethatexistinOffice365.OncethevictimdecidestoacceptpermissionstotheappbyclickingYES,ourplatformreceivesanAccessTokenthatwouldallowinvoketheWindowsLiveAPItoaccessallthegrantedresources(seePicture29).Asyoucansee, intheexistingdeploymentatpresentWindowsLivedoesnotallowtoaccesse-mail,althoughtheScopesarealreadydefined for it. They are currently in a migration process that have not yet beenconcludedandwhichwillsoonmakeavailabletheaccesstoallmailboxes.

Page 22: RansomCloud O365: Pay por your Office 365 e-mail

22

Picture29:AvalidAccessTokenforastolenWindowsLive

Fromtheplatformitispossible,however,touseotherAPIs,suchasaccesscontactsorfilestorageOneDriveservice.AspartofthedemowehaveimplementedtheaccesstoOneDrive in a graphicalway, so that itwould be enoughwith just one click on theOneDrivebuttontoaccessthestructuredocumentscontained(seePicture30).

Picture30:AccessingdocumentsinOneDrivefolders

This way you can download all the files, browse folders (see Picture 31) to look for documents and, even, launch search queries of words within documents, which would help find information in a much more targeted way.

Page 23: RansomCloud O365: Pay por your Office 365 e-mail

23

Picture31:WiththeOneDriveAPIinWindowsLiveyoucansearchfordocs

SimilarlytomessagesfromOffice365,withRansomCloudyoucanaccessfiles,deletethemfromtheiroriginallocation,encryptthemasithasbeendonewithmessagesoftheemail anddeposit seized in the folderof the victimalongwith a file to explainwhattheprocesshastobefollowedfordecryptingfiles.9.-AppreviewinsidetheIdentityProvidersThe first recommendation service theMicrosoft Office 365, Gmail orWindows Livecloudusersmustfollowistoreviewwhatappstheyhaveconnectedtotheir identityandwhatpermissionstheyhavebeengrantedtoeachofthem(seePicture32).

Picture32:AmaliciousappconnectedtoGoogle'saccount

Keep in mind that the Sappo platform and RansomCloud module can continue tooperateandcapturingthenewarrivingemailswhiletheobtainedOAuthtokenisstillvalid or the access to it hasn’t yet been revoked. It is therefore important to checkwhatappsarenoacceptedandeliminatesuspicious.

Page 24: RansomCloud O365: Pay por your Office 365 e-mail

24

AcuriousthingisthatnewappswithpermissionsgrantedtotheMicrosoftOffice365accounts takes a while to appear andwhen they appear, do not have to allow theaccesstothedetailed informationof theapp(seePicture33).Mostoften, theusualwayistorequestthepermits informationfromtheappandnotbeingabletoaccessthemwithOffice365iftheappismaliciousastheonecreatedhere.

Picture33:AppwithpermitsintheOffice365userprofile

AsinthecaseofMicrosoftOffice365,withWindowsLiveyoucanseethepermissionsgrantedtotheapps(seePicture34).Inthiscase,itisalsopossibletoseeindetailallthepermissionsthateachoftheassociatedappshaswiththeaccount.YouhavegototheApplicationsandServicesareaandthereyouwillfindtheapp.Andifweclickonthedetailsyoucanseethedetailedlistofallthepermissionsthathavebeengrantedtothisapp.

Picture34:Thelistofthepermitsgrantedtothisapp

Page 25: RansomCloud O365: Pay por your Office 365 e-mail

25

DependingonwhattheIdentityProvideristhefunctionsthatcouldbeperformedwiththistypeofmaliciousAppschange,buttheconceptwillalwaysbethesame.GettinganAccessTokenforanumberofScopesandimplementaccess.10.-RecommendationsagainstSpearAppsattacksInthisarticlewehavebeenshownhowyoucanusemaliciousappsconnectedtoanIdP for amaliciouspurpose. The conceptproofof thishasbeen intended toexplainhow easy it can be tomigrate a scheme from the world of cybercrime as it is theransomwaretothecloud.Topreventtheseattacksyoumuststrengthensecuritymeasurestobetakenagainstthe Spear Apps attacks and these are some of the recommendations that can befollowed, in addition to strengthening email systems to themaximumwith second-factor authentication, antispam engines and antimalware powerful or protectionsagainstidentityspoofingusingSPFfilters.10.1.-NewsafetytrainingforusersAswehavebeentellingthroughoutthearticle,intheendthemostimportantproblemisthatwehavebeentraininguserstodetectaveryspecifictypeofphishingattackinwhich credentials, through a Web page hosted on a hacked server or a false one,where we cannot correctly identify the domain of the site, but all theserecommendationsfailwhenwetalkaboutaSpearAppattack(seePicture35).

Picture35:Adoberecommendationstorecognizephishingattacks

Intheseattacks,whentheuserhastoclickonYESitdoesitintheoriginalWebsiteofMicrosoft.HeisinsidetheMicrosoft.comdomain,underaHTTPsconnection,withanExtended Validation Digital Certificate - Green – which is correct and belongs toMicrosoft,andbesidesthisitneverrequestsanyuserorpassword.Everythinglearnedsofaritwon’tbeofmuchuse.Besides all this, the AntiPhishing filter implemented in browsers cannot detectanythingbecausetheURLwhereyouare istherightoneofMicrosoft,thereforewillnotblockit.YouhavetotrainuserstodetectsuchSpearAppsattacks,besidestrainingthemtodetecttheSpearPhishingones.

Page 26: RansomCloud O365: Pay por your Office 365 e-mail

26

10.2.-TheuseoftheSOC’sCloudOne of the important recommendations that can be done is to practice activemonitoring(seePicture36)ofabnormalsituations,throughananalysisofthelogsthatCloudprovidersareoffering.

Picture36:CloudSecurityMonitoringbasedonLogTrusttechnology

InMicrosoft Office 365 it is possible to access the activity logs of all accounts of acorporatedomainsotoproceedwithitsactivityanalysis.ACloudIntrusionDetectionSystem(CloudIDS)whichanalyzestheselogstodetectabnormalpatternsorunusualbehavior could detect the onset of a new app associated with a mailbox or thebeginningoftheactivityofanapp,RansomCloudtype,actingononeofthemailboxes.

Picture37:OperatingdiagramofBlueCoatElasticatechnology

Page 27: RansomCloud O365: Pay por your Office 365 e-mail

27

TechnologiessuchasLogTrust,https://www.logtrust.com,whichallowstheanalyzeofall logs and create usage rules or solutions such as Elastica,https://www.bluecoat.com, fromBlueCoat (seePicture37) can support this typeofjobstobeperformedbythesafetyequipmentofacompany.10.3.-Solutions:PublicCloudEncryptionFinally,anotherpossibleoptiontopreventdatatheftbymaliciousappscouldbethethe use of encryption solutions of public cloud data. In this case, a solution likeVaultive,http://vaultive.com/,whichencryptsOffice365wouldfigure,that ifanappgetspermissiontoaccessemailsthroughanAccessToken,thisappcannotaccessthedecrypteddataaccountifitisnotdonethroughthecorporategatewaythatperformsencryptionanddecryptionofdata(seePicture38).

Picture38:Office365EncryptionwithaVaultiveGateway

This solution does not protect against an attack from Ransom Cloud, but againstespionagemessagesoranaccountfilesofoneoftheIdPsmentionedinthisarticle.IfthemaliciousappgottheAccessToken,buttriestoaccessfromoutsidethecompanynetwork -without going through the gateway that encrypts anddecrypts thepubliccloud - then would get all the data of email messages encrypted, as shown in thepicture39.

Picture39:EmailencryptionOffice365withVaultive

Amaliciousapplicationcouldcontinuedestroying themailsor continue toaccessingthelistofsenders,butcouldneverreadtheemailsfromthemailboxasallofthemareencrypted.

Page 28: RansomCloud O365: Pay por your Office 365 e-mail

28

10.4.-Applicationofthe2ndFactorAuthorizationsolutionsCurrentlythemainIdPsapplyidentityprotectionsolutionsinasingleentrypoint,suchas the login process. In this section, the usermust provide the system's credentialsverificationofa secondauthentication factor, suchasa telephone terminal inwhichGoogleAuthenticatorisusedorOTPcodesarereceivedthroughaSMSmessage.

Picture40:Latchisa2ndFactorAuthorizationtocontrolaccesspermissionsinapps

However,ifanattackerisabletostealaTokenOAuth,protectionslikeSecondFactorAuthentication won’t protect the account. It would therefore be necessary to addSecond FactorAuthorization solutions forwhich theuser couldnotonlyprotect theloginbuttheactionshewantsenabledornotoneachoftheaccounts.We could have a protection type Latch (2FAutorización solution,https://latch.elevenpaths.com)toenabletheownertomanageidentityifyouwanttoturnonoroffcertainaccountfeaturessotopreventthistypeofsolutions.11.-FinalthoughtsThesetechniquesarenotnew,andintheworldofcybercrimehavebeenoccasionallyusedinmanyattackscenarios.InthepasttherehavebeenSPAMPhishingattacksforTokens OAuth, but it is important that those responsible for the identities in theorganizations to be fully aware of the dangers that these attacks are greater thantypicalSpearPhishingattacks-alreadyverydangeroustocompanies.Of course, companies responsible for the IdPs -Microsoft andGoogle– should takeactions and detect malicious activity by connected apps with the sole purpose ofremovingthemassoonaspossiblefromtheirsystemsandrevoketheiraccess.