pax_global_header00006660000000000000000000000064136305056470014523gustar00rootroot0000000000000052 comment=e95526d06cd4d8869befb79a26ade8bbc2262265 nmrpflash-0.9.14-16-ge95526d/000077500000000000000000000000001363050564700152045ustar00rootroot00000000000000nmrpflash-0.9.14-16-ge95526d/.gitignore000066400000000000000000000000701363050564700171710ustar00rootroot00000000000000*.o *.swp *.img *.pcap *.dni Makefile.win WpdPack/ Obj/ nmrpflash-0.9.14-16-ge95526d/LICENSE000066400000000000000000001045131363050564700162150ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . nmrpflash-0.9.14-16-ge95526d/Makefile000066400000000000000000000025531363050564700166510ustar00rootroot00000000000000CC ?= gcc PREFIX ?= /usr/local VERSION = $(shell git describe --always | tail -c +2) LIBS = -lpcap CFLAGS += -Wall -g -DNMRPFLASH_VERSION=\"$(VERSION)\" LDFLAGS += $(LIBS) ifeq ($(shell uname -s),Linux) CFLAGS += $(shell pkg-config libnl-route-3.0 --cflags) LIBS += $(shell pkg-config libnl-route-3.0 --libs) endif nmrpflash_OBJ = nmrp.o tftp.o ethsock.o main.o util.o .PHONY: clean install release release/macos release/linux release/win32 nmrpflash: $(nmrpflash_OBJ) $(CC) $(CFLAGS) -o nmrpflash $(nmrpflash_OBJ) $(LDFLAGS) tftptest: CFLAGS=-DNMRPFLASH_TFTP_TEST make clean nmrpflash %.o: %.c nmrpd.h $(CC) -c $(CFLAGS) $< -o $@ fuzz: clean CC=afl-gcc CFLAGS=-DNMRPFLASH_FUZZ make nmrpflash mv nmrpflash fuzz dofuzz: fuzz echo core | sudo tee /proc/sys/kernel/core_pattern echo performance | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor afl-fuzz -i fuzzin -o fuzzout -- ./fuzz echo powersave | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor clean: rm -f $(nmrpflash_OBJ) nmrpflash install: nmrpflash install -m 755 nmrpflash $(PREFIX)/bin release/macos: CFLAGS="-mmacosx-version-min=10.6" make release zip nmrpflash-$(VERSION)-macos.zip nmrpflash release/linux: release zip nmrpflash-$(VERSION)-linux.zip nmrpflash release/win32: zip nmrpflash-$(VERSION)-win32.zip nmrpflash.exe release: clean nmrpflash strip nmrpflash nmrpflash-0.9.14-16-ge95526d/README.md000066400000000000000000000154431363050564700164720ustar00rootroot00000000000000nmrpflash - Netgear Unbrick Utility ==================================== `nmrpflash` uses Netgear's [NMRP protocol](http://www.chubb.wattle.id.au/PeterChubb/nmrp.html) to flash a new firmware image to a compatible device. It has been successfully used on a Netgear EX2700, DNG3700v2, R6220, R7000, D7000, WNR3500, R6400 and R6800, but is likely to be compatible with many other Netgear devices. Prebuilt binaries for Linux, ~OS X~ macOS and Windows are available [here](https://github.com/jclehner/nmrpflash/releases) ([Npcap](https://nmap.org/npcap/) is required on Windows). ``` Usage: nmrpflash [OPTIONS...] Options (-i, and -f or -c are mandatory): -a IP address to assign to target device -A IP address to assign to selected interface -B Blind mode (don't wait for response packets) -c Command to run before (or instead of) TFTP upload -f Firmware file -F Remote filename to use during TFTP upload -i Network interface directly connected to device -m MAC address of target device (xx:xx:xx:xx:xx:xx) -M Subnet mask to assign to target device -t Timeout (in milliseconds) for NMRP packets -T Time (seconds) to wait after successfull TFTP upload -p Port to use for TFTP upload -R Set device region (NA, WW, GR, PR, RU, BZ, IN, KO, JP) -v Be verbose -V Print version and exit -L List network interfaces -h Show this screen ``` ### Using nmrpflash Your Netgear router must be connected to your network using an Ethernet cable. The device running `nmrpflash` must be connected to the same network, using either Wi-Fi or Ethernet. All available network interfaces can be listed using ``` # nmrpflash -L eth0 192.168.1.2 f2:11:a1:02:03:b1 ``` Once you've determined the interface to use, we can flash the image. Firmware images can usually be downloaded directly from Netgear. Power on your device immediately after starting `nmrpflash`. ``` # nmrpflash -i eth0 -f EX2700-V1.0.1.8.img Advertising NMRP server on eth0 ... / Received configuration request from a4:2b:8c:00:00:01. Sending configuration: 10.164.183.252/24 Received upload request: filename 'firmware'. Uploading EX2700-V1.0.1.8.img ... Upload successful. Waiting for remote to respond. Remote finished. Closing connection. Reboot your device now. ``` ### Common issues In any case, run `nmrpflash` with `-vvv` before filing a bug report. Also, try connecting your Netgear router *directly* to the computer running `nmrpflash`. ###### "Error while loading shared libraries: ..." (Linux) You must install your Linux distribution's `libpcap` and `libnl-3` packages (exact names will vary depending on your distribution). ###### "The program can't start because wpcap.dll is missing" (Windows) Install [Npcap](https://nmap.org/npcap/). For `nmrpflash` versions prior to 0.9.14, install Npcap with "WinPcap Compatibility" enabled. Version 0.9.13 is the last version to support Windows XP. ###### "No suitable network interfaces found." Make sure the network interface is up (wireless interfaces are not supported). On Windows, try restarting the WinPcap service (commands must be run as administrator): ``` C:\> net stop npf C:\> net start npf ``` ###### "No response after 60 seconds. Bailing out." The router did not respond. Always run `nmrpflash` in the following manner: * Turn off the router. * Run `nmrpflash`. * Turn on the router. If that still doesn't work, you can try "blind mode", which can be invoked using `-B`. Note that you also have to specify your router's mac address using `-m xx:xx:xx:xx:xx:xx`. Also beware that in this mode, careful timing between running `nmrpflash` and turning on the router may be required! It's also possible that your device does not support the NMRP protocol. ###### "Timeout while waiting for ACK(0)/OACK." The device did not respond to `nmrpflash`'s TFTP upload request. By default, `nmrpflash` will assign `10.164.183.252` to the target device, while adding `10.164.183.253` to the network interface specified by the `-i` flag. You can use `-a` to change the IP address assigned to the target (e.g. if your network is `192.168.1.0/24`, specify a *free* IP address, such as `-a 192.168.1.252`), and `-A` to change the IP address used for the network interface. This error message could also indicate a bug in the TFTP code; try using an external tftp client (busybox in this example), by specifying the `-c` flag instead of the `-f` flag: `# nmrpflash -i eth0 -c 'busybox tftp -p -l EX2700-V1.0.1.8.img $IP'` The environment variable `IP` is set by `nmrpflash` (other environment variables are: `MAC`, `PORT`, `NETMASK`). ###### "Timeout while waiting for CLOSE_REQ." After a successful file upload, `nmrpflash` waits for up to 5 minutes for an answer from your device. You can increase this by specifying a longer timeout using `-T` switch (argument is in seconds). It's entirely possible that the image was flashed successfully, but the operation took longer than 5 minutes. ###### "Address X/Y cannot be used on interface Z." `nmrpflash` refuses to use an IP address / subnet mask combination that would make the remote device unreachable from the device running `nmrpflash`. For example, if the IP address of your computer is 192.168.0.1/255.255.255.0, assigning 192.168.2.1/255.255.255.0 to the router makes no sense, because the TFTP upload will fail. ###### "IP address of X has changed. Please assign a static IP to the interface." This can happen if the network interface in question automatically detects that the network cable has been connected, and your computer tries to reconfigure that interface (NetworkManager on Linux does this for example) - this can usually be disabled. An alternative would be to add `-c 'ifconfig '` to the command line, for example: `# nmrpflash -i eth0 -a 192.168.1.1 -f firmware.bin -c 'ifconfig eth0 192.168.1.2'` This will execute the command specified by `-c` prior to starting the TFTP upload (in this case setting the IP address to 192.168.1.2). ###### "Received keep-alive request." This usually means that flashing is in progress. On some devices, you may get a few hundred keep-alive requests before it eventually finishes! ###### "TFTP block rollover. Upload might fail!" By default, file transfers using TFTP are limited to `65535 * 512` bytes (almost 32 MiB). Uploading files exceeding this limit might fail, depending on the device. ### Building and installing ###### Linux, Mac OS X, BSDs ``` $ make && sudo make install ``` ###### Windows The repository includes a [DevCpp](http://sourceforge.net/projects/orwelldevcpp/) project file (`nmrpflash.dev`). Download the latest [Npcap SDK](https://nmap.org/npcap/) and extract it into the root folder of the `nmrpflash` sources. nmrpflash-0.9.14-16-ge95526d/ethsock.c000066400000000000000000000533621363050564700170210ustar00rootroot00000000000000/** * nmrpflash - Netgear Unbrick Utility * Copyright (C) 2016 Joseph Lehner * * nmrpflash is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * nmrpflash is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with nmrpflash. If not, see . * */ #include #include #include #include #include #include #include #include "nmrpd.h" #if defined(NMRPFLASH_WINDOWS) #define NMRPFLASH_NETALIAS_PREFIX "net" #define WPCAP #include #else #include #include #include #include #include #if defined(NMRPFLASH_LINUX) #define NMRPFLASH_AF_PACKET AF_PACKET #include #include #include #else #define NMRPFLASH_AF_PACKET AF_LINK #include #include #endif #endif struct ethsock { const char *intf; pcap_t *pcap; #ifndef NMRPFLASH_WINDOWS int fd; #ifdef NMRPFLASH_LINUX bool stp; #endif #else HANDLE handle; DWORD index; #endif unsigned timeout; uint8_t hwaddr[6]; }; struct ethsock_arp_undo { uint32_t ipaddr; uint8_t hwaddr[6]; }; struct ethsock_ip_undo { #ifndef NMRPFLASH_WINDOWS uint32_t ip[2]; #else ULONG context; #endif }; const char *mac_to_str(uint8_t *mac) { static char buf[18]; snprintf(buf, sizeof(buf), "%02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); return buf; } static int x_pcap_findalldevs(pcap_if_t **devs) { char errbuf[PCAP_ERRBUF_SIZE]; if (pcap_findalldevs(devs, errbuf) != 0) { fprintf(stderr, "%s.\n", errbuf); return -1; } return 0; } #ifndef NMRPFLASH_LINUX static int systemf(const char *fmt, ...) { char cmd[1024]; int ret; va_list va; va_start(va, fmt); ret = vsnprintf(cmd, sizeof(cmd) - 1, fmt, va); if (ret >= sizeof(cmd) - 1) { return -1; } ret = system(cmd); va_end(va); return ret; } #endif #ifndef NMRPFLASH_WINDOWS static inline bool sockaddr_get_hwaddr(struct sockaddr *sa, uint8_t *hwaddr) { void *src; if (sa->sa_family != NMRPFLASH_AF_PACKET) { return false; } #ifndef NMRPFLASH_LINUX if (((struct sockaddr_dl*)sa)->sdl_type != IFT_ETHER) { return false; } src = LLADDR((struct sockaddr_dl*)sa); #else src = ((struct sockaddr_ll*)sa)->sll_addr; #endif memcpy(hwaddr, src, 6); return true; } #ifdef NMRPFLASH_LINUX static int bridge_stp_state(const char *intf) { char name[256]; snprintf(name, sizeof(name), "/sys/class/net/%s/bridge/stp_state", intf); return open(name, O_RDWR, 0644); } static bool bridge_stp_enabled(const char *intf) { char c; int fd = bridge_stp_state(intf); if (fd == -1) { return false; } if (read(fd, &c, 1) != 1) { c = '0'; } close(fd); return c == '1'; } static bool bridge_stp(const char *intf, bool enabled) { bool ret; const char *s = enabled ? "1\n" : "0\n"; int fd = bridge_stp_state(intf); if (fd == -1) { return false; } ret = (write(fd, s, 2) == 2); close(fd); return ret; } static struct nl_addr *build_ip(uint32_t ip) { struct nl_addr *na = nl_addr_build(AF_INET, &ip, 4); if (!na) { xperror("nl_addr_build"); } return na; } static struct nl_sock *xnl_socket_route() { int err; struct nl_sock *sk = nl_socket_alloc(); if (sk) { if (!(err = nl_connect(sk, NETLINK_ROUTE))) { return sk; } nl_socket_free(sk); nl_perror(err, "nl_connect"); } else { xperror("nl_socket_alloc"); } return NULL; } static bool intf_add_del_ip(const char *intf, uint32_t ipaddr, uint32_t ipmask, bool add) { struct rtnl_addr *ra = NULL; struct nl_sock *sk = NULL; struct nl_addr *na = NULL; int err = 1; if (!(sk = xnl_socket_route())) { return false; } if (!(ra = rtnl_addr_alloc())) { xperror("rtnl_addr_alloc"); goto out; } rtnl_addr_set_ifindex(ra, if_nametoindex(intf)); if (!(na = build_ip(ipaddr))) { goto out; } nl_addr_set_prefixlen(na, bitcount(ipmask)); rtnl_addr_set_local(ra, na); nl_addr_put(na); if (!(na = build_ip((ipaddr & ipmask) | ~ipmask))) { goto out; } rtnl_addr_set_broadcast(ra, na); nl_addr_put(na); if ((err = add ? rtnl_addr_add(sk, ra, 0) : rtnl_addr_delete(sk, ra, 0)) < 0) { if (add && err == -NLE_EXIST) { err = 0; } else if (add || verbosity > 1) { nl_perror(err, add ? "rtnl_addr_add" : "rtnl_addr_delete"); } } out: rtnl_addr_put(ra); nl_socket_free(sk); return !err; } static bool intf_add_del_arp(const char *intf, uint32_t ipaddr, uint8_t *hwaddr, bool add) { #if 0 struct arpreq arp; memset(&arp, 0, sizeof(arp)); arp.arp_ha.sa_family = ARPHRD_ETHER; memcpy(&arp.arp_ha.sa_data, hwaddr, 6); arp.arp_flags = ATF_PERM | ATF_COM; struct sockaddr_in *in = (struct sockaddr_in*)&req.arp_pa; in->sin_addr.s_addr = htonl(ipaddr); in->sin_family = AF_INET; int fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) { perror("socket"); return false; } bool ret = true; if (ioctl(fd, add ? SIOCSARP : SIOCDARP, &req) < 0) { perror(add ? "ioctl(SIOCSARP)" : "ioctl(SIOCDARP"); ret = false; } close(fd); return ret; #else struct nl_sock *sk; struct rtnl_neigh *neigh; struct nl_addr *mac, *ip; int err = 1; sk = NULL; neigh = NULL; mac = ip = NULL; if (!(sk = xnl_socket_route())) { goto out; } if (!(neigh = rtnl_neigh_alloc())) { xperror("rtnl_neigh_alloc"); goto out; } if (!(mac = nl_addr_build(AF_PACKET, hwaddr, 6))) { xperror("nl_addr_build"); goto out; } if (!(ip = nl_addr_build(AF_INET, &ipaddr, 4))) { xperror("nl_addr_build"); goto out; } rtnl_neigh_set_ifindex(neigh, if_nametoindex(intf)); rtnl_neigh_set_dst(neigh, ip); err = rtnl_neigh_delete(sk, neigh, 0); if (add) { rtnl_neigh_set_lladdr(neigh, mac); rtnl_neigh_set_state(neigh, NUD_PERMANENT); err = rtnl_neigh_add(sk, neigh, NLM_F_CREATE); } if (err && (add || verbosity > 1)) { nl_perror(err, add ? "rtnl_neigh_add" : "rtnl_neigh_delete"); } out: nl_addr_put(ip); nl_addr_put(mac); rtnl_neigh_put(neigh); nl_socket_free(sk); return !err; #endif } #endif static bool intf_get_info(const char *intf, uint8_t *hwaddr, bool *bridge) { struct ifaddrs *ifas, *ifa; bool found; if (getifaddrs(&ifas) != 0) { xperror("getifaddrs"); return false; } found = false; if (bridge) { *bridge = false; } for (ifa = ifas; ifa; ifa = ifa->ifa_next) { if (!strcmp(ifa->ifa_name, intf)) { if (sockaddr_get_hwaddr(ifa->ifa_addr, hwaddr)) { #ifdef NMRPFLASH_BSD if (bridge) { *bridge = ((struct if_data*) ifa->ifa_data)->ifi_type == IFT_BRIDGE; } #endif found = true; break; } } } freeifaddrs(ifas); return found; } #else void win_perror2(const char *msg, DWORD err) { char *buf = NULL; FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&buf, 0, NULL); if (buf) { /* FormatMessageA terminates buf with CRLF! */ fprintf(stderr, "%s: %s", msg, buf); LocalFree(buf); } else { fprintf(stderr, "%s: error %d\n", msg, (int)err); } } static bool intf_get_info(const char *intf, uint8_t *hwaddr, DWORD *index) { PIP_ADAPTER_INFO adapters, adapter; DWORD ret; ULONG i, bufLen = 0; bool found = false; if ((ret = GetAdaptersInfo(NULL, &bufLen)) != ERROR_BUFFER_OVERFLOW) { win_perror2("GetAdaptersInfo", ret); return false; } adapters = malloc(bufLen); if (!adapters) { xperror("malloc"); return false; } if ((ret = GetAdaptersInfo(adapters, &bufLen) == NO_ERROR)) { for (adapter = adapters; adapter; adapter = adapter->Next) { if (adapter->Type != MIB_IF_TYPE_ETHERNET && adapter->Type != IF_TYPE_IEEE80211) { continue; } /* Interface names from WinPcap are "\Device\NPF_{GUID}", while * AdapterName from GetAdaptersInfo is just "{GUID}".*/ if (strstr(intf, adapter->AdapterName)) { if (adapter->AddressLength == 6) { memcpy(hwaddr, adapter->Address, 6); if (index) { *index = adapter->Index; } found = true; break; } } } } else { win_perror2("GetAdaptersInfo", ret); } free(adapters); return found; } static const char *intf_alias_to_wpcap(const char *intf) { static char buf[128]; pcap_if_t *devs, *dev; unsigned i = 0, dev_num = 0; if (intf[0] == '\\') { return intf; } else if (sscanf(intf, NMRPFLASH_NETALIAS_PREFIX "%u", &dev_num) != 1) { fprintf(stderr, "Invalid interface alias.\n"); return NULL; } if (x_pcap_findalldevs(&devs) != 0) { return NULL; } for (dev = devs; dev; dev = dev->next, ++i) { if (i == dev_num) { if (verbosity) { printf("%s%u: %s\n", NMRPFLASH_NETALIAS_PREFIX, i, dev->name); } strncpy(buf, dev->name, sizeof(buf) - 1); buf[sizeof(buf) - 1] = '\0'; break; } } pcap_freealldevs(devs); if (!dev) { fprintf(stderr, "Interface alias not found.\n"); return NULL; } return buf; } static const char *intf_get_pretty_name(const char *intf) { static char buf[512]; char *guid; HKEY hkey; LONG err; DWORD len; guid = strstr(intf, "NPF_{"); if (!guid) { return NULL; } guid += 4; snprintf(buf, sizeof(buf), "System\\CurrentControlSet\\Control\\Network\\" "{4D36E972-E325-11CE-BFC1-08002BE10318}\\" "%s\\Connection", guid); err = RegOpenKeyExA(HKEY_LOCAL_MACHINE, buf, 0, KEY_READ, &hkey); if (err != ERROR_SUCCESS) { if (verbosity > 1) { win_perror2("RegOpenKeyExA", err); } return NULL; } len = sizeof(buf); err = RegQueryValueExA(hkey, "Name", NULL, NULL, (LPBYTE)buf, &len); if (err == ERROR_SUCCESS) { intf = buf; } else { if (verbosity > 1) { win_perror2("RegQueryValueExA", err); } intf = NULL; } RegCloseKey(hkey); return intf; } #endif inline uint8_t *ethsock_get_hwaddr(struct ethsock *sock) { return sock->hwaddr; } struct ethsock *ethsock_create(const char *intf, uint16_t protocol) { char buf[PCAP_ERRBUF_SIZE]; struct bpf_program fp; struct ethsock *sock; bool is_bridge; int err; #ifdef NMRPFLASH_WINDOWS intf = intf_alias_to_wpcap(intf); if (!intf) { return NULL; } #endif sock = malloc(sizeof(struct ethsock)); if (!sock) { xperror("malloc"); return NULL; } buf[0] = '\0'; sock->intf = intf; sock->pcap = pcap_open_live(sock->intf, BUFSIZ, 1, 1, buf); if (!sock->pcap) { fprintf(stderr, "%s.\n", buf); goto cleanup; } if (*buf) { fprintf(stderr, "Warning: %s.\n", buf); } if (pcap_datalink(sock->pcap) != DLT_EN10MB) { fprintf(stderr, "%s is not an ethernet interface.\n", intf); goto cleanup; } #ifndef NMRPFLASH_WINDOWS err = !intf_get_info(intf, sock->hwaddr, &is_bridge); #else err = !intf_get_info(intf, sock->hwaddr, &sock->index); #endif if (err) { fprintf(stderr, "Failed to get interface info.\n"); goto cleanup; } #ifndef NMRPFLASH_WINDOWS sock->fd = pcap_get_selectable_fd(sock->pcap); if (sock->fd == -1) { pcap_perror(sock->pcap, "pcap_get_selectable_fd"); goto cleanup; } #else sock->handle = pcap_getevent(sock->pcap); if (!sock->handle) { pcap_perror(sock->pcap, "pcap_getevent"); goto cleanup; } err = pcap_setmintocopy(sock->pcap, 1); if (err) { pcap_perror(sock->pcap, "pcap_setmintocopy"); goto cleanup; } #endif snprintf(buf, sizeof(buf), "ether proto 0x%04x and not ether src %s", protocol, mac_to_str(sock->hwaddr)); err = pcap_compile(sock->pcap, &fp, buf, 0, 0); if (err) { pcap_perror(sock->pcap, "pcap_compile"); goto cleanup; } err = pcap_setfilter(sock->pcap, &fp); pcap_freecode(&fp); if (err) { pcap_perror(sock->pcap, "pcap_setfilter"); goto cleanup; } #ifdef NMRPFLASH_LINUX // nmrpflash does not work on bridge interfaces with STP enabled if ((sock->stp = bridge_stp_enabled(intf))) { if (!bridge_stp(intf, false)) { fprintf(stderr, "Warning: failed to disable STP on %s.\n", intf); } } #else if (is_bridge) { fprintf(stderr, "Warning: bridge interfaces are not fully " "supported on this platform.\n"); } #endif return sock; cleanup: ethsock_close(sock); return NULL; } int select_fd(int fd, unsigned timeout) { struct timeval tv; int status; fd_set fds; FD_ZERO(&fds); FD_SET(fd, &fds); tv.tv_sec = timeout / 1000000; tv.tv_usec = timeout % 1000000; status = select(fd + 1, &fds, NULL, NULL, &tv); if (status < 0) { sock_perror("select"); } return status; } ssize_t ethsock_recv(struct ethsock *sock, void *buf, size_t len) { struct pcap_pkthdr* hdr; const u_char *capbuf; int status; #ifdef NMRPFLASH_WINDOWS DWORD ret; if (sock->timeout) { ret = WaitForSingleObject(sock->handle, sock->timeout); if (ret == WAIT_TIMEOUT) { return 0; } else if (ret != WAIT_OBJECT_0) { win_perror2("WaitForSingleObject", ret); return -1; } } #else if (sock->timeout) { status = select_fd(sock->fd, sock->timeout); if (status < 0) { return -1; } else if (status == 0) { return 0; } } #endif status = pcap_next_ex(sock->pcap, &hdr, &capbuf); switch (status) { case 1: memcpy(buf, capbuf, MIN(len, hdr->caplen)); return hdr->caplen; case 0: return 0; case -1: pcap_perror(sock->pcap, "pcap_next_ex"); return -1; default: fprintf(stderr, "pcap_next_ex: returned %d.\n", status); return -1; } } int ethsock_send(struct ethsock *sock, void *buf, size_t len) { #ifdef NMRPFLASH_WINDOWS if (pcap_sendpacket(sock->pcap, buf, len) == 0) { return 0; } else { pcap_perror(sock->pcap, "pcap_sendpacket"); return -1; } #else if (pcap_inject(sock->pcap, buf, len) == len) { return 0; } else { pcap_perror(sock->pcap, "pcap_inject"); return -1; } #endif } int ethsock_close(struct ethsock *sock) { if (!sock) { return 0; } #ifdef NMRPFLASH_LINUX if (sock->stp) { bridge_stp(sock->intf, true); } #endif if (sock->pcap) { pcap_close(sock->pcap); } free(sock); return 0; } inline int ethsock_set_timeout(struct ethsock *sock, unsigned msec) { sock->timeout = msec; return 0; } static int ethsock_arp(struct ethsock *sock, uint8_t *hwaddr, uint32_t ipaddr, struct ethsock_arp_undo **undo) { #if defined(NMRPFLASH_UNIX) && !defined(NMRPFLASH_LINUX) struct in_addr addr = { .s_addr = ipaddr }; #elif defined(NMRPFLASH_WINDOWS) DWORD err; MIB_IPNETROW arp = { .dwIndex = sock->index, .dwPhysAddrLen = 6, .dwAddr = ipaddr, .dwType = MIB_IPNET_TYPE_STATIC }; memcpy(arp.bPhysAddr, hwaddr, 6); #endif if (undo) { #if defined(NMRPFLASH_LINUX) if (!intf_add_del_arp(sock->intf, ipaddr, hwaddr, true)) { return -1; } #elif defined(NMRPFLASH_WINDOWS) err = CreateIpNetEntry(&arp); if (err != NO_ERROR) { win_perror2("CreateIpNetEntry", err); return -1; } #else if (systemf("arp -s %s %s", inet_ntoa(addr), mac_to_str(hwaddr)) != 0) { return -1; } #endif *undo = malloc(sizeof(struct ethsock_arp_undo)); if (!*undo) { xperror("malloc"); return -1; } (*undo)->ipaddr = ipaddr; memcpy((*undo)->hwaddr, hwaddr, 6); } else { #if defined(NMRPFLASH_LINUX) if (!intf_add_del_arp(sock->intf, ipaddr, hwaddr, false)) { return -1; } #elif defined(NMRPFLASH_WINDOWS) return DeleteIpNetEntry(&arp) ? 0 : -1; #else return systemf("arp -d %s", inet_ntoa(addr)); #endif } return 0; } int ethsock_arp_add(struct ethsock *sock, uint8_t *hwaddr, uint32_t ipaddr, struct ethsock_arp_undo **undo) { ethsock_arp(sock, hwaddr, ipaddr, NULL); return undo ? ethsock_arp(sock, hwaddr, ipaddr, undo) : -1; } int ethsock_arp_del(struct ethsock *sock, struct ethsock_arp_undo **undo) { if (!*undo) { return 0; } int ret = ethsock_arp(sock, (*undo)->hwaddr, (*undo)->ipaddr, NULL); free(*undo); *undo = NULL; return ret; } static bool get_hwaddr_from_pcap(const pcap_if_t *dev, uint8_t *hwaddr) { #ifndef NMRPFLASH_WINDOWS pcap_addr_t *addr; int i; for (addr = dev->addresses; addr; addr = addr->next) { if (verbosity > 1) { printf("%s: sa_family=%d, sa_data={ ", dev->name, addr->addr->sa_family); for (i = 0; i != sizeof(addr->addr->sa_data); ++i) { printf("%02x ", addr->addr->sa_data[i] & 0xff); } printf("}\n"); } if (sockaddr_get_hwaddr(addr->addr, hwaddr)) { return true; } } #endif return intf_get_info(dev->name, hwaddr, NULL); } int ethsock_list_all(void) { pcap_if_t *devs, *dev; pcap_addr_t *addr; uint8_t hwaddr[6]; unsigned dev_num = 0, dev_ok = 0; #ifdef NMRPFLASH_WINDOWS const char *pretty; #endif if (x_pcap_findalldevs(&devs) != 0) { return -1; } memset(hwaddr, 0, 6); for (dev = devs; dev; dev = dev->next, ++dev_num) { if (dev->flags & PCAP_IF_LOOPBACK) { if (verbosity) { printf("%-15s (loopback device)\n", dev->name); } continue; } if (!get_hwaddr_from_pcap(dev, hwaddr)) { if (verbosity) { printf("%-15s (not an ethernet device)\n", dev->name); } continue; } #ifndef NMRPFLASH_WINDOWS printf("%-15s", dev->name); #else /* Call this here so *_perror() calls don't happen within a line */ pretty = intf_get_pretty_name(dev->name); if (!verbosity) { printf("%s%-2u", NMRPFLASH_NETALIAS_PREFIX, dev_num); } else { printf("%s", dev->name); } #endif for (addr = dev->addresses; addr; addr = addr->next) { if (addr->addr->sa_family == AF_INET) { printf(" %-15s", inet_ntoa(((struct sockaddr_in*)addr->addr)->sin_addr)); break; } } if (!addr) { printf(" %-15s", "0.0.0.0"); } printf(" %s", mac_to_str(hwaddr)); #ifdef NMRPFLASH_WINDOWS if (pretty) { printf(" (%s)", pretty); } else if (dev->description) { printf(" (%s)", dev->description); } #endif printf("\n"); ++dev_ok; } if (!dev_ok) { printf("No suitable network interfaces found.\n"); } return 0; } int ethsock_for_each_ip(struct ethsock *sock, ethsock_ip_callback_t callback, void *arg) { struct ethsock_ip_callback_args args; pcap_if_t *devs, *dev; pcap_addr_t *addr; int status = 0; if (x_pcap_findalldevs(&devs) != 0) { return -1; } args.arg = arg; for (dev = devs; dev; dev = dev->next) { if (strcmp(sock->intf, dev->name)) { continue; } for (addr = dev->addresses; addr; addr = addr->next) { if (addr->addr->sa_family == AF_INET) { args.ipaddr = &((struct sockaddr_in*)addr->addr)->sin_addr; args.ipmask = &((struct sockaddr_in*)addr->netmask)->sin_addr; status = callback(&args); if (status <= 0) { break; } } } break; } pcap_freealldevs(devs); return status <= 0 ? status : 0; } static inline void set_addr(void *p, uint32_t addr) { struct sockaddr_in* sin = p; sin->sin_family = AF_INET; sin->sin_addr.s_addr = addr; #ifdef NMRPFLASH_BSD ((struct sockaddr*)p)->sa_len = sizeof(struct sockaddr_in); #endif } #if !defined(NMRPFLASH_WINDOWS) && !defined(NMRPFLASH_LINUX) static bool intf_up(int fd, const char *intf, bool up) { struct ifreq ifr; strncpy(ifr.ifr_name, intf, IFNAMSIZ); if (ioctl(fd, SIOCGIFFLAGS, &ifr) != 0) { if (up) { xperror("ioctl(SIOCGIFFLAGS)"); } return false; } if (!up) { ifr.ifr_flags &= ~(IFF_UP | IFF_RUNNING); } else { ifr.ifr_flags |= IFF_UP | IFF_RUNNING; } if (ioctl(fd, SIOCSIFFLAGS, &ifr) != 0) { if (up) { xperror("ioctl(SIOCSIFFLAGS)"); } return false; } return true; } #endif static int ethsock_ip_add_del(struct ethsock *sock, uint32_t ipaddr, uint32_t ipmask, struct ethsock_ip_undo **undo, bool add) { int ret, fd; if (add && undo) { if (!(*undo = malloc(sizeof(struct ethsock_ip_undo)))) { xperror("malloc"); return -1; } memset(*undo, 0, sizeof(**undo)); } ret = -1; fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) { sock_perror("socket"); goto out; } #ifndef NMRPFLASH_WINDOWS #ifdef NMRPFLASH_LINUX if (add) { (*undo)->ip[0] = ipaddr; (*undo)->ip[1] = ipmask; } if (!intf_add_del_ip(sock->intf, (*undo)->ip[0], (*undo)->ip[1], add)) { goto out; } #else // NMRPFLASH_OSX (or any other BSD) struct ifaliasreq ifra; memset(&ifra, 0, sizeof(ifra)); strncpy(ifra.ifra_name, sock->intf, IFNAMSIZ); set_addr(&ifra.ifra_addr, ipaddr); set_addr(&ifra.ifra_mask, ipmask); //set_addr(&ifra.ifra_broadaddr, (ipaddr & ipmask) | ~ipmask); if (ioctl(fd, add ? SIOCAIFADDR : SIOCDIFADDR, &ifra) != 0) { if (add) { xperror("ioctl(SIOCAIFADDR"); } goto out; } if (add) { (*undo)->ip[0] = ipaddr; (*undo)->ip[1] = ipmask; intf_up(fd, ifra.ifra_name, true); } #endif #else // NMRPFLASH_WINDOWS struct sockaddr_in sin; ULONG instance; (*undo)->context = 0; DWORD err = AddIPAddress(ipaddr, ipmask, sock->index, &(*undo)->context, &instance); if (err != NO_ERROR && err != ERROR_DUP_DOMAINNAME && err != ERROR_OBJECT_ALREADY_EXISTS) { win_perror2("AddIPAddress", err); goto out; } set_addr(&sin, ipaddr); time_t beg = time_monotonic(); /* Wait until the new IP has actually been added */ while (bind(fd, (struct sockaddr*)&sin, sizeof(sin)) != 0) { if ((time_monotonic() - beg) >= 5) { fprintf(stderr, "Failed to bind after 5 seconds: "); sock_perror("bind"); DeleteIPAddress((*undo)->context); goto out; } } #endif ret = 0; out: #ifndef NMRPFLASH_WINDOWS close(fd); #else closesocket(fd); #endif if (ret != 0 && undo) { free(*undo); *undo = NULL; } return ret; } int ethsock_ip_add(struct ethsock *sock, uint32_t ipaddr, uint32_t ipmask, struct ethsock_ip_undo **undo) { return ethsock_ip_add_del(sock, ipaddr, ipmask, undo, true); } int ethsock_ip_del(struct ethsock *sock, struct ethsock_ip_undo **undo) { if (!*undo) { return 0; } int ret; #ifndef NMRPFLASH_WINDOWS if ((*undo)->ip[0] != INADDR_NONE) { ret = ethsock_ip_add_del(sock, (*undo)->ip[0], (*undo)->ip[1], undo, false); } else { ret = 0; } #else ret = DeleteIPAddress((*undo)->context) ? 0 : -1; #endif free(*undo); *undo = NULL; return ret; } nmrpflash-0.9.14-16-ge95526d/main.c000066400000000000000000000157431363050564700163060ustar00rootroot00000000000000/** * nmrpflash - Netgear Unbrick Utility * Copyright (C) 2016 Joseph Lehner * * nmrpflash is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * nmrpflash is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with nmrpflash. If not, see . * */ #include #include #include #include #include "nmrpd.h" int verbosity = 0; void usage(FILE *fp) { fprintf(fp, "Usage: nmrpflash [OPTIONS...]\n" "\n" "Options (-i, and -f or -c are mandatory):\n" " -a IP address to assign to target device\n" " -A IP address to assign to selected interface\n" " -B Blind mode (don't wait for response packets)\n" " -c Command to run before (or instead of) TFTP upload\n" " -f Firmware file\n" " -F Remote filename to use during TFTP upload\n" " -i Network interface directly connected to device\n" " -m MAC address of target device (xx:xx:xx:xx:xx:xx)\n" " -M Subnet mask to assign to target device\n" " -t Timeout (in milliseconds) for NMRP packets\n" " -T Time (seconds) to wait after successfull TFTP upload\n" " -p Port to use for TFTP upload\n" #ifdef NMRPFLASH_SET_REGION " -R Set device region (NA, WW, GR, PR, RU, BZ, IN, KO, JP)\n" #endif #ifdef NMRPFLASH_TFTP_TEST " -U Test TFTP upload\n" #endif " -v Be verbose\n" " -V Print version and exit\n" " -L List network interfaces\n" " -h Show this screen\n" "\n" "Example: (run as " #ifndef NMRPFLASH_WINDOWS "root" #else "administrator" #endif ")\n\n" #ifndef NMRPFLASH_WINDOWS "# nmrpflash -i eth0 -f firmware.bin\n" #else "C:\\> nmrpflash.exe -i net0 -f firmware.bin\n" #endif "\n" "When using -c, the environment variables IP, PORT, NETMASK\n" "and MAC are set to the device IP address, TFTP port, subnet\n" "mask and MAC address, respectively.\n" "\n" "nmrpflash %s, Copyright (C) 2016 Joseph C. Lehner\n" "nmrpflash is free software, licensed under the GNU GPLv3.\n" "Source code at https://github.com/jclehner/nmrpflash\n" "\n", NMRPFLASH_VERSION ); } #ifdef NMRPFLASH_WINDOWS void require_admin() { SID_IDENTIFIER_AUTHORITY auth = SECURITY_NT_AUTHORITY; PSID group = NULL; BOOL admin, success = AllocateAndInitializeSid( &auth, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &group ); if (success) { success = CheckTokenMembership(NULL, group, &admin); FreeSid(group); if (success) { if (!admin) { fprintf(stderr, "Error: must be run as administrator\n"); exit(1); } else { return; } } } fprintf(stderr, "Warning: failed to check administrator privileges\n"); } void show_exit_prompt() { DWORD pid; HWND win = GetConsoleWindow(); if (!win || !GetWindowThreadProcessId(win, &pid)) { return; } if (GetCurrentProcessId() == pid) { printf("Press any key to exit\n"); getch(); } } #else void require_admin() { if (getuid() != 0) { fprintf(stderr, "Error: must be run as root\n"); exit(1); } } #endif int main(int argc, char **argv) { int c, val, max; bool list = false, have_dest_mac = false; struct nmrpd_args args = { .rx_timeout = 200 * 1000, .ul_timeout = 5 * 60 * 1000, .tftpcmd = NULL, .file_local = NULL, .file_remote = NULL, .ipaddr_intf = NULL, .ipaddr = NULL, .ipmask = "255.255.255.0", .intf = NULL, .mac = "ff:ff:ff:ff:ff:ff", .op = NMRP_UPLOAD_FW, .port = 69, .region = NULL, .blind = false, }; #ifdef NMRPFLASH_WINDOWS char *newpath = NULL; char *oldpath = NULL; char *windir = NULL; WSADATA wsa; atexit(&show_exit_prompt); val = WSAStartup(MAKEWORD(2, 2), &wsa); if (val != 0) { win_perror2("WSAStartup", val); return 1; } #ifndef _WIN64 // This dirty hack works around the WOW64 file system redirector[1], which would prevent // us from calling programs residing in %windir%\System32 when running on a 64bit system // (since nmrpflash is currently shipped as 32bit only). // // [1] https://msdn.microsoft.com/en-us/library/windows/desktop/aa384187(v=vs.85).aspx oldpath = getenv("PATH"); windir = getenv("WINDIR"); if (oldpath && windir) { newpath = malloc(strlen(oldpath) + strlen(windir) + 32); sprintf(newpath, "%s;%s\\Sysnative", oldpath, windir); SetEnvironmentVariable("PATH", newpath); free(newpath); } #endif #endif opterr = 0; while ((c = getopt(argc, argv, "a:A:Bc:f:F:i:m:M:p:R:t:T:hLVvU")) != -1) { max = 0x7fffffff; switch (c) { case 'a': args.ipaddr = optarg; break; case 'A': args.ipaddr_intf = optarg; break; case 'B': args.blind = true; break; case 'c': args.tftpcmd = optarg; break; case 'f': args.file_local = optarg; break; case 'F': args.file_remote = optarg; break; case 'i': args.intf = optarg; break; case 'm': args.mac = optarg; have_dest_mac = true; break; case 'M': args.ipmask = optarg; break; #ifdef NMRPFLASH_SET_REGION case 'R': args.region = optarg; break; #endif case 'p': case 'T': case 't': if (c == 'p') { max = 0xffff; } val = atoi(optarg); if (val <= 0 || val > max) { fprintf(stderr, "Invalid numeric value for -%c.\n", c); return 1; } if (c == 'p') { args.port = val; } else if (c == 't') { args.rx_timeout = val * 1000; } else if (c == 'T') { args.ul_timeout = val * 1000; } break; case 'V': printf("nmrpflash %s\n", NMRPFLASH_VERSION); val = 0; goto out; case 'v': ++verbosity; break; case 'L': list = true; break; case 'h': usage(stdout); val = 0; goto out; #ifdef NMRPFLASH_TFTP_TEST case 'U': if (args.ipaddr && args.file_local) { val = tftp_put(&args); goto out; } /* fall through */ #endif default: usage(stderr); val = 1; goto out; } } if (args.ipaddr_intf && !args.ipaddr) { fprintf(stderr, "Error: cannot use -A without using -a .\n"); return 1; } if (args.blind && !have_dest_mac) { fprintf(stderr, "Error: use of -B requires -m .\n"); return 1; } #ifndef NMRPFLASH_FUZZ if (!list && ((!args.file_local && !args.tftpcmd) || !args.intf)) { usage(stderr); return 1; } if (!list) { require_admin(); } #endif val = !list ? nmrp_do(&args) : ethsock_list_all(); out: #ifdef NMRPFLASH_WINDOWS WSACleanup(); #endif return val; } nmrpflash-0.9.14-16-ge95526d/nmrp.c000066400000000000000000000403541363050564700163320ustar00rootroot00000000000000/** * nmrpflash - Netgear Unbrick Utility * Copyright (C) 2016 Joseph Lehner * * nmrpflash is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * nmrpflash is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with nmrpflash. If not, see . * */ #include #include #include #include #include #include #include #include "nmrpd.h" #define NMRP_HDR_LEN 6 #define NMRP_OPT_HDR_LEN 4 #define NMRP_MIN_PKT_LEN (sizeof(struct eth_hdr) + NMRP_HDR_LEN) #define ETH_P_NMRP 0x0912 #ifndef PACKED #define PACKED __attribute__((__packed__)) #endif #ifdef NMRPFLASH_WINDOWS #define setenv(name, value, overwrite) SetEnvironmentVariable(name, value) #endif enum nmrp_code { NMRP_C_NONE = 0, NMRP_C_ADVERTISE = 1, NMRP_C_CONF_REQ = 2, NMRP_C_CONF_ACK = 3, NMRP_C_CLOSE_REQ = 4, NMRP_C_CLOSE_ACK = 5, NMRP_C_KEEP_ALIVE_REQ = 6, NMRP_C_KEEP_ALIVE_ACK = 7, NMRP_C_TFTP_UL_REQ = 16 }; enum nmrp_opt_type { NMRP_O_MAGIC_NO = 0x0001, NMRP_O_DEV_IP = 0x0002, NMRP_O_DEV_REGION = 0x0004, NMRP_O_FW_UP = 0x0101, NMRP_O_ST_UP = 0x0102, NMRP_O_FILE_NAME = 0x0181 }; struct nmrp_opt { uint16_t type; uint16_t len; char val[1]; } PACKED; struct nmrp_msg { uint16_t reserved; uint8_t code; uint8_t id; uint16_t len; char opts[44]; } PACKED; struct nmrp_pkt { struct eth_hdr eh; struct nmrp_msg msg; } PACKED; static const char *msg_code_str(uint16_t code) { #define MSG_CODE(x) case NMRP_C_ ## x: return #x static char buf[16]; switch (code) { MSG_CODE(ADVERTISE); MSG_CODE(CONF_REQ); MSG_CODE(CONF_ACK); MSG_CODE(CLOSE_REQ); MSG_CODE(CLOSE_ACK); MSG_CODE(KEEP_ALIVE_REQ); MSG_CODE(KEEP_ALIVE_ACK); MSG_CODE(TFTP_UL_REQ); default: snprintf(buf, sizeof(buf), "%04x", ntohs(code)); return buf; } #undef MSG_CODE } static uint16_t to_region_code(const char *region) { #define REGION_CODE(r, c) if (!strcasecmp(region, r)) return htons(c) REGION_CODE("NA", 0x0001); REGION_CODE("WW", 0x0002); REGION_CODE("GR", 0x0003); REGION_CODE("PR", 0x0004); REGION_CODE("RU", 0x0005); REGION_CODE("BZ", 0x0006); REGION_CODE("IN", 0x0007); REGION_CODE("KO", 0x0008); REGION_CODE("JP", 0x0009); #undef REGION_CODE return 0; } static void msg_dump(struct nmrp_msg *msg) { int rem; fprintf(stderr, "res=0x%04x, code=0x%02x, id=0x%02x, len=%u", ntohs(msg->reserved), msg->code, msg->id, ntohs(msg->len)); rem = ntohs(msg->len) - NMRP_HDR_LEN; fprintf(stderr, "%s\n", rem ? "" : " (no opts)"); } static void *msg_opt(struct nmrp_msg *msg, uint16_t type, uint16_t* len) { struct nmrp_opt* opt = (struct nmrp_opt*)msg->opts; size_t rem = ntohs(msg->len) - NMRP_HDR_LEN; uint16_t olen; do { olen = ntohs(opt->len); if (olen < NMRP_OPT_HDR_LEN || olen > rem) { break; } if (ntohs(opt->type) == type) { if (len) { *len = olen; } return opt->val; } opt = (struct nmrp_opt*)(((char *)opt) + olen); rem -= olen; } while (rem); return NULL; } static char *msg_filename(struct nmrp_msg *msg) { static char buf[256]; uint16_t len; char *p = msg_opt(msg, NMRP_O_FILE_NAME, &len); if (p) { len = MIN(sizeof(buf) - 1, len); memcpy(buf, p, len); buf[len] = '\0'; return buf; } return NULL; } static inline void msg_init(struct nmrp_msg *msg, uint16_t code) { memset(msg, 0, sizeof(*msg)); msg->len = htons(NMRP_HDR_LEN); msg->code = code; } static char *msg_mkopt(struct nmrp_msg *msg, char *p, uint16_t type, const void *val, size_t len) { struct nmrp_opt* opt = (struct nmrp_opt*)p; len &= 0xffff; msg->len = ntohs(msg->len); if ((msg->len + len > sizeof(*msg))) { fprintf(stderr, "Error: invalid option - this is a bug\n"); exit(1); } opt->type = htons(type); opt->len = NMRP_OPT_HDR_LEN + len; if (val) { memcpy(opt->val, val, len); } msg->len += opt->len; p += opt->len; msg->len = htons(msg->len); opt->len = htons(opt->len); return p; } static void msg_mkadvertise(struct nmrp_msg *msg, const char *magic) { msg_init(msg, NMRP_C_ADVERTISE); msg_mkopt(msg, msg->opts, NMRP_O_MAGIC_NO, magic, strlen(magic)); } static void msg_mkconfack(struct nmrp_msg *msg, uint32_t ipaddr, uint32_t ipmask, uint16_t region) { char *p; uint32_t ip[2] = { ipaddr, ipmask }; msg_init(msg, NMRP_C_CONF_ACK); p = msg_mkopt(msg, msg->opts, NMRP_O_DEV_IP, &ip, 8); p = msg_mkopt(msg, p, NMRP_O_FW_UP, NULL, 0); #ifdef NMRPFLASH_SET_REGION if (region) { p = msg_mkopt(msg, p, NMRP_O_DEV_REGION, ®ion, 2); } #endif } #ifdef NMRPFLASH_FUZZ #define NMRP_INITIAL_TIMEOUT 0 #define ethsock_create(a, b) ((struct ethsock*)1) #define ethsock_get_hwaddr(a) ethsock_get_hwaddr_fake(a) #define ethsock_recv(sock, buf, len) read(STDIN_FILENO, buf, len) #define ethsock_send(a, b, c) (0) #define ethsock_set_timeout(a, b) (0) #define ethsock_arp_add(a, b, c, d) (0) #define ethsock_arp_del(a, b) (0) #define ethsock_ip_add(a, b, c, d) (0) #define ethsock_ip_del(a, b) (0) #define ethsock_close(a) (0) #define tftp_put(a) (0) static uint8_t *ethsock_get_hwaddr_fake(struct ethsock* sock) { static uint8_t hwaddr[6] = { 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa }; return hwaddr; } #else #define NMRP_INITIAL_TIMEOUT 60 #endif static int pkt_send(struct ethsock *sock, struct nmrp_pkt *pkt) { return ethsock_send(sock, pkt, sizeof(*pkt)); } static int pkt_recv(struct ethsock *sock, struct nmrp_pkt *pkt) { ssize_t bytes, mlen; memset(pkt, 0, sizeof(*pkt)); bytes = ethsock_recv(sock, pkt, sizeof(*pkt)); if (bytes < 0) { return 1; } else if (!bytes) { return 2; } mlen = ntohs(pkt->msg.len); if (bytes < (mlen + sizeof(pkt->eh)) || bytes < NMRP_MIN_PKT_LEN || mlen < NMRP_HDR_LEN) { fprintf(stderr, "Short packet (%d raw, %d message)\n", (int)bytes, (int)mlen); return 1; } else if (mlen > sizeof(pkt->msg)) { printf("Truncating %d byte message.\n", (int)mlen); pkt->msg.len = htons(sizeof(pkt->msg)); } return 0; } static int mac_parse(const char *str, uint8_t *hwaddr) { int i; unsigned data[6]; sscanf(str, "%02x:%02x:%02x:%02x:%02x:%02x%n", data, data + 1, data + 2, data + 3, data + 4, data + 5, &i); if (i == strlen(str)) { for (i = 0; i != 6; ++i) { if (data[i] > 255) { break; } hwaddr[i] = data[i] & 0xff; } if (i == 6) { return 1; } } return 0; } struct is_valid_ip_arg { struct in_addr *ipaddr; struct in_addr *ipmask; int result; }; static int is_valid_ip_cb(struct ethsock_ip_callback_args *args) { #define SUBNET(x) ((x)->ipaddr->s_addr & (x)->ipmask->s_addr) struct is_valid_ip_arg *arg = args->arg; if (SUBNET(args) == SUBNET(arg)) { arg->result = args->ipaddr->s_addr != arg->ipaddr->s_addr; return 0; } return 1; #undef SUBNET } static int is_valid_ip(struct ethsock *sock, struct in_addr *ipaddr, struct in_addr *ipmask) { int status; struct is_valid_ip_arg arg = { .ipaddr = ipaddr, .ipmask = ipmask, .result = 0 }; status = ethsock_for_each_ip(sock, is_valid_ip_cb, &arg); return status < 0 ? status : arg.result; } static void sigh(int sig) { g_interrupted = 1; } static const char *spinner = "\\|/-"; int nmrp_do(struct nmrpd_args *args) { struct nmrp_pkt tx, rx; uint8_t *src, dest[6]; uint16_t region; char *filename; time_t beg; int i, timeout, status, ulreqs, expect, upload_ok, autoip, ka_reqs, fake; struct ethsock *sock; struct ethsock_ip_undo *ip_undo = NULL; struct ethsock_arp_undo *arp_undo = NULL; uint32_t intf_addr; void (*sigh_orig)(int); struct in_addr ipaddr; struct in_addr ipmask; if (args->op != NMRP_UPLOAD_FW) { fprintf(stderr, "Operation not implemented.\n"); return 1; } if (!mac_parse(args->mac, dest)) { fprintf(stderr, "Invalid MAC address '%s'.\n", args->mac); return 1; } ipmask.s_addr = inet_addr(args->ipmask); if (ipmask.s_addr == INADDR_NONE || netmask(bitcount(ipmask.s_addr)) != ipmask.s_addr) { fprintf(stderr, "Invalid subnet mask '%s'.\n", args->ipmask); return 1; } if (!args->ipaddr) { autoip = true; /* A random IP address. The MAC of the first device that was * used to test this utility starts with a4:2b:8c, so we use * 164 (0xa4) and 183 (0x2b + 0x8c). * * These addresses should not cause collisions on most networks, * and if they do, the user is probably "poweruser" enough to * be able to use the -a and -A options. */ args->ipaddr = "10.164.183.252"; if (!args->ipaddr_intf) { args->ipaddr_intf = "10.164.183.253"; } } else if (args->ipaddr_intf) { autoip = true; } else { autoip = false; } if ((ipaddr.s_addr = inet_addr(args->ipaddr)) == INADDR_NONE) { fprintf(stderr, "Invalid IP address '%s'.\n", args->ipaddr); return 1; } if (args->ipaddr_intf && (intf_addr = inet_addr(args->ipaddr_intf)) == INADDR_NONE) { fprintf(stderr, "Invalid IP address '%s'.\n", args->ipaddr_intf); return 1; } if (args->file_local && strcmp(args->file_local, "-") && access(args->file_local, R_OK) == -1) { fprintf(stderr, "Error accessing file '%s'.\n", args->file_local); return 1; } if (args->file_remote) { if (!tftp_is_valid_filename(args->file_remote)) { fprintf(stderr, "Invalid remote filename '%s'.\n", args->file_remote); return 1; } } if (args->region) { region = to_region_code(args->region); if (!region) { fprintf(stderr, "Invalid region code '%s'.\n", args->region); return 1; } } else { region = 0; } status = 1; sock = ethsock_create(args->intf, ETH_P_NMRP); if (!sock) { return 1; } sigh_orig = signal(SIGINT, sigh); if (!autoip) { status = is_valid_ip(sock, &ipaddr, &ipmask); if (status <= 0) { if (!status) { fprintf(stderr, "Address %s/%s cannot be used on interface %s.\n", args->ipaddr, args->ipmask, args->intf); } goto out; } } else { if (verbosity) { printf("Adding %s to interface %s.\n", args->ipaddr_intf, args->intf); } if (ethsock_ip_add(sock, intf_addr, ipmask.s_addr, &ip_undo) != 0) { goto out; } } if (ethsock_set_timeout(sock, args->rx_timeout)) { goto out; } src = ethsock_get_hwaddr(sock); if (!src) { goto out; } memcpy(tx.eh.ether_shost, src, 6); memcpy(tx.eh.ether_dhost, dest, 6); tx.eh.ether_type = htons(ETH_P_NMRP); msg_mkadvertise(&tx.msg, "NTGR"); i = 0; upload_ok = 0; fake = 0; timeout = args->blind ? 10 : NMRP_INITIAL_TIMEOUT; beg = time_monotonic(); while (!g_interrupted) { printf("\rAdvertising NMRP server on %s ... %c", args->intf, spinner[i]); fflush(stdout); i = (i + 1) & 3; if (pkt_send(sock, &tx) < 0) { goto out; } status = pkt_recv(sock, &rx); if (status == 0) { if (memcmp(rx.eh.ether_dhost, src, 6) == 0) { break; } else if (verbosity) { printf("\nIgnoring bogus response: %s -> %s.\n", mac_to_str(rx.eh.ether_shost), mac_to_str(rx.eh.ether_dhost)); } } else if (status == 1) { goto out; } else { /* because we don't want nmrpflash's exit status to be zero */ status = 1; if ((time_monotonic() - beg) >= timeout) { printf("\nNo response after %d seconds. ", timeout); if (!args->blind) { printf("Bailing out.\n"); goto out; } else { // we're blind, so fake a response from the MAC specified by -m memcpy(rx.eh.ether_shost, dest, 6); msg_init(&rx.msg, NMRP_C_CONF_REQ); printf("Continuing blindly."); fake = 1; break; } } } } printf("\n"); memcpy(tx.eh.ether_dhost, rx.eh.ether_shost, 6); if (ethsock_arp_add(sock, rx.eh.ether_shost, ipaddr.s_addr, &arp_undo) != 0) { goto out; } expect = NMRP_C_CONF_REQ; ulreqs = 0; ka_reqs = 0; while (!g_interrupted) { if (expect != NMRP_C_NONE && rx.msg.code != expect) { fprintf(stderr, "Received %s while waiting for %s!\n", msg_code_str(rx.msg.code), msg_code_str(expect)); } msg_init(&tx.msg, NMRP_C_NONE); status = 1; switch (rx.msg.code) { case NMRP_C_ADVERTISE: printf("Received NMRP advertisement from %s.\n", mac_to_str(rx.eh.ether_shost)); status = 1; goto out; case NMRP_C_CONF_REQ: msg_mkconfack(&tx.msg, ipaddr.s_addr, ipmask.s_addr, region); expect = NMRP_C_TFTP_UL_REQ; if (!fake) { printf("Received configuration request from %s.\n", mac_to_str(rx.eh.ether_shost)); } printf("Sending configuration: %s/%d.\n", args->ipaddr, bitcount(ipmask.s_addr)); break; case NMRP_C_TFTP_UL_REQ: if (!upload_ok) { if (++ulreqs > 5) { printf("Bailing out after %d upload requests.\n", ulreqs); tx.msg.code = NMRP_C_CLOSE_REQ; break; } } else { if (verbosity) { printf("Ignoring extra upload request.\n"); } ethsock_set_timeout(sock, args->ul_timeout); tx.msg.code = NMRP_C_KEEP_ALIVE_REQ; break; } filename = msg_filename(&rx.msg); if (filename) { if (!args->file_remote) { args->file_remote = filename; } printf("Received upload request: filename '%s'.\n", filename); } else if (!args->file_remote) { args->file_remote = leafname(args->file_local); if (!fake) { printf("Received upload request without filename.\n"); } } status = 0; if (args->tftpcmd) { printf("Executing '%s' ... \n", args->tftpcmd); setenv("IP", inet_ntoa(ipaddr), 1); setenv("PORT", lltostr(args->port, 10), 1); setenv("MAC", mac_to_str(rx.eh.ether_shost), 1); setenv("NETMASK", inet_ntoa(ipmask), 1); //setenv("FILENAME", args->file_remote ? args->file_remote : "", 1); status = system(args->tftpcmd); } if (!status && args->file_local) { if (!autoip) { status = is_valid_ip(sock, &ipaddr, &ipmask); if (status < 0) { goto out; } else if (!status) { printf("IP address of %s has changed. Please assign a " "static ip to the interface.\n", args->intf); tx.msg.code = NMRP_C_CLOSE_REQ; break; } } if (verbosity) { printf("Using remote filename '%s'.\n", args->file_remote); } if (!strcmp(args->file_local, "-")) { printf("Uploading from stdin ... "); } else { printf("Uploading %s ... ", leafname(args->file_local)); } fflush(stdout); if (!(status = tftp_put(args))) { printf("OK\n"); } } if (!status) { if (args->blind) { goto out; } printf("Waiting for remote to respond.\n"); upload_ok = 1; ethsock_set_timeout(sock, args->ul_timeout); tx.msg.code = NMRP_C_KEEP_ALIVE_REQ; expect = NMRP_C_NONE; } else if (status == -2) { expect = NMRP_C_TFTP_UL_REQ; } else { goto out; } break; case NMRP_C_KEEP_ALIVE_REQ: tx.msg.code = NMRP_C_KEEP_ALIVE_ACK; ethsock_set_timeout(sock, args->ul_timeout); printf("\rReceived keep-alive request (%d). ", ++ka_reqs); break; case NMRP_C_CLOSE_REQ: tx.msg.code = NMRP_C_CLOSE_ACK; break; case NMRP_C_CLOSE_ACK: status = 0; goto out; default: fprintf(stderr, "Unknown message code 0x%02x!\n", rx.msg.code); msg_dump(&rx.msg); } if (tx.msg.code != NMRP_C_NONE) { if (pkt_send(sock, &tx) != 0 || tx.msg.code == NMRP_C_CLOSE_REQ) { goto out; } } if (rx.msg.code == NMRP_C_CLOSE_REQ) { if (ka_reqs) { printf("\n"); } printf("Remote finished. Closing connection.\n"); break; } status = pkt_recv(sock, &rx); if (status) { if (status == 2) { if (!args->blind) { fprintf(stderr, "Timeout while waiting for %s.\n", msg_code_str(expect)); goto out; } // fake response msg_init(&rx.msg, expect); memcpy(rx.eh.ether_shost, tx.eh.ether_dhost, 6); fake = 1; } else { goto out; } } else { fake = 0; } ethsock_set_timeout(sock, args->rx_timeout); } if (!g_interrupted) { status = 0; if (ulreqs) { printf("Reboot your device now.\n"); } else { printf("No upload request received.\n"); } } out: signal(SIGINT, sigh_orig); ethsock_arp_del(sock, &arp_undo); ethsock_ip_del(sock, &ip_undo); ethsock_close(sock); return status; } nmrpflash-0.9.14-16-ge95526d/nmrpd.h000066400000000000000000000100461363050564700164760ustar00rootroot00000000000000/** * nmrpflash - Netgear Unbrick Utility * Copyright (C) 2016 Joseph Lehner * * nmrpflash is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * nmrpflash is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with nmrpflash. If not, see . * */ #ifndef NMRPD_H #define NMRPD_H #include #include #include #if defined(_WIN32) || defined(_WIN64) # define NMRPFLASH_WINDOWS #elif defined(__APPLE__) && defined(__MACH__) # define NMRPFLASH_UNIX # define NMRPFLASH_OSX # define NMRPFLASH_BSD #elif defined (__unix__) # define NMRPFLASH_UNIX # if defined(__linux__) # define NMRPFLASH_LINUX # elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || defined(__OpenBSD__) # define NMRPFLASH_BSD # else # warning "nmrpflash is not fully supported on this platform" # endif #else # warning "nmrpflash is not supported on this platform" #endif #ifndef NMRPFLASH_WINDOWS #include #include #include #include #include #ifndef NMRPFLASH_LINUX #include #endif #else #include #include #include #include #endif #ifndef MIN #define MIN(a, b) ((a) < (b) ? (a) : (b)) #endif #ifndef MAX #define MAX(a, b) ((a) > (b) ? (a) : (b)) #endif #ifndef PACKED #define PACKED __attribute__((packed)) #endif #define NMRPFLASH_SET_REGION struct eth_hdr { uint8_t ether_dhost[6]; uint8_t ether_shost[6]; uint16_t ether_type; } PACKED; enum nmrp_op { NMRP_UPLOAD_FW = 0, NMRP_UPLOAD_ST = 1, NMRP_SET_REGION = 2, }; struct nmrpd_args { unsigned rx_timeout; unsigned ul_timeout; const char *tftpcmd; const char *file_local; const char *file_remote; const char *ipaddr_intf; const char *ipaddr; const char *ipmask; const char *intf; const char *mac; enum nmrp_op op; bool blind; uint16_t port; const char *region; }; const char *leafname(const char *path); int tftp_put(struct nmrpd_args *args); bool tftp_is_valid_filename(const char *filename); int nmrp_do(struct nmrpd_args *args); int select_fd(int fd, unsigned timeout); const char *mac_to_str(uint8_t *mac); #ifdef NMRPFLASH_WINDOWS void win_perror2(const char *msg, DWORD err); void sock_perror(const char *msg); #else #define sock_perror(x) xperror(x) #endif extern int verbosity; struct ethsock; struct ethsock_arp_undo; struct ethsock_ip_undo; struct ethsock *ethsock_create(const char *intf, uint16_t protocol); int ethsock_close(struct ethsock *sock); int ethsock_send(struct ethsock *sock, void *buf, size_t len); ssize_t ethsock_recv(struct ethsock *sock, void *buf, size_t len); int ethsock_set_timeout(struct ethsock *sock, unsigned msec); uint8_t *ethsock_get_hwaddr(struct ethsock *sock); int ethsock_arp_add(struct ethsock *sock, uint8_t *hwaddr, uint32_t ipaddr, struct ethsock_arp_undo **undo); int ethsock_arp_del(struct ethsock *sock, struct ethsock_arp_undo **undo); int ethsock_list_all(void); struct ethsock_ip_callback_args { struct in_addr *ipaddr; struct in_addr *ipmask; void *arg; }; typedef int (*ethsock_ip_callback_t)(struct ethsock_ip_callback_args *args); int ethsock_for_each_ip(struct ethsock *sock, ethsock_ip_callback_t callback, void *arg); int ethsock_ip_add(struct ethsock *sock, uint32_t ipaddr, uint32_t ipmask, struct ethsock_ip_undo **undo); int ethsock_ip_del(struct ethsock *sock, struct ethsock_ip_undo **undo); time_t time_monotonic(); char *lltostr(long long ll, int base); uint32_t bitcount(uint32_t n); uint32_t netmask(uint32_t count); void xperror(const char *msg); extern volatile sig_atomic_t g_interrupted; #endif nmrpflash-0.9.14-16-ge95526d/nmrpflash.dev000066400000000000000000000032011363050564700176720ustar00rootroot00000000000000[Project] FileName=nmrpflash.dev Name=nmrpflash Type=1 Ver=2 ObjFiles= Includes=Npcap\Include Libs=Npcap\Lib PrivateResource= ResourceIncludes= MakeIncludes= Compiler=-DNMRPFLASH_VERSION=\"0.9.14\"_@@_ -D_WIN32_WINNT=0x0600 CppCompiler= Linker=-liphlpapi_@@_-lws2_32_@@_-ladvapi32_@@_-lwpcap_@@_-lpacket_@@__@@_ IsCpp=0 Icon= ExeOutput= ObjectOutput=Obj LogOutput= LogOutputEnabled=0 OverrideOutput=0 OverrideOutputName=nmrpflash.exe HostApplication= UseCustomMakefile=0 CustomMakefile= CommandLine=-L Folders= IncludeVersionInfo=0 SupportXPThemes=0 CompilerSet=3 CompilerSettings=0000000100000000000001000 UnitCount=6 [VersionInfo] Major=1 Minor=0 Release=0 Build=0 LanguageID=1033 CharsetID=1252 CompanyName= FileVersion=1.0.0.0 FileDescription=Developed using the Dev-C++ IDE InternalName= LegalCopyright= LegalTrademarks= OriginalFilename= ProductName= ProductVersion=1.0.0.0 AutoIncBuildNr=0 SyncProduct=1 [Unit1] FileName=ethsock.c CompileCpp=0 Folder= Compile=1 Link=1 Priority=1000 OverrideBuildCmd=0 BuildCmd= [Unit2] FileName=main.c CompileCpp=0 Folder= Compile=1 Link=1 Priority=1000 OverrideBuildCmd=0 BuildCmd= [Unit3] FileName=nmrp.c CompileCpp=0 Folder= Compile=1 Link=1 Priority=1000 OverrideBuildCmd=0 BuildCmd= [Unit4] FileName=tftp.c CompileCpp=0 Folder= Compile=1 Link=1 Priority=1000 OverrideBuildCmd=0 BuildCmd= [Unit5] FileName=nmrpd.h CompileCpp=0 Folder= Compile=1 Link=1 Priority=1000 OverrideBuildCmd=0 BuildCmd= [Unit6] FileName=util.c CompileCpp=0 Folder= Compile=1 Link=1 Priority=1000 OverrideBuildCmd=0 BuildCmd= nmrpflash-0.9.14-16-ge95526d/nmrpflash.manifest000066400000000000000000000007541363050564700207340ustar00rootroot00000000000000 nmrpflash nmrpflash-0.9.14-16-ge95526d/nmrpflash.rc000066400000000000000000000001311363050564700175170ustar00rootroot00000000000000#include "winuser.h" CREATEPROCESS_MANIFEST_RESOURCE_ID RT_MANIFEST nmrpflash.manifest nmrpflash-0.9.14-16-ge95526d/tftp.c000066400000000000000000000240461363050564700163330ustar00rootroot00000000000000/** * nmrpflash - Netgear Unbrick Utility * Copyright (C) 2016 Joseph Lehner * * nmrpflash is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * nmrpflash is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with nmrpflash. If not, see . * */ #include #include #include #include #include #include #include #include "nmrpd.h" #ifndef O_BINARY #define O_BINARY 0 #endif #define TFTP_BLKSIZE 1456 static const char *opcode_names[] = { "RRQ", "WRQ", "DATA", "ACK", "ERR", "OACK" }; enum tftp_opcode { RRQ = 1, WRQ = 2, DATA = 3, ACK = 4, ERR = 5, OACK = 6 }; static bool is_netascii(const char *str) { uint8_t *p = (uint8_t*)str; for (; *p; ++p) { if (*p < 0x20 || *p > 0x7f) { return false; } } return true; } static inline char *pkt_mknum(char *pkt, uint16_t n) { *(uint16_t*)pkt = htons(n); return pkt + 2; } static inline uint16_t pkt_num(char *pkt) { return ntohs(*(uint16_t*)pkt); } static char *pkt_mkopt(char *pkt, const char *opt, const char* val) { strcpy(pkt, opt); pkt += strlen(opt) + 1; strcpy(pkt, val); pkt += strlen(val) + 1; return pkt; } static bool pkt_nextstr(char **pkt, char **str, size_t *rem) { size_t len; if (!isprint(**pkt) || !(len = strnlen(*pkt, *rem))) { return false; } else if (str) { *str = *pkt; } *pkt += len + 1; if (*rem > 1) { *rem -= len + 1; } else { *rem = 0; } return true; } static bool pkt_nextopt(char **pkt, char **opt, char **val, size_t *rem) { return pkt_nextstr(pkt, opt, rem) && pkt_nextstr(pkt, val, rem); } static char *pkt_optval(char* pkt, const char* name) { size_t rem = 512; char *opt, *val; pkt += 2; while (pkt_nextopt(&pkt, &opt, &val, &rem)) { if (!strcasecmp(name, opt)) { return val; } } return NULL; } static size_t pkt_xrqlen(char *pkt) { size_t rem = 512; pkt += 2; while (pkt_nextopt(&pkt, NULL, NULL, &rem)) { ; } return 514 - rem; } static void pkt_mkwrq(char *pkt, const char *filename, unsigned blksize) { filename = leafname(filename); if (!tftp_is_valid_filename(filename)) { fprintf(stderr, "Overlong/illegal filename; using 'firmware'.\n"); filename = "firmware"; } else if (!strcmp(filename, "-")) { filename = "firmware"; } pkt = pkt_mknum(pkt, WRQ); pkt = pkt_mkopt(pkt, filename, "octet"); if (blksize && blksize != 512) { pkt = pkt_mkopt(pkt, "blksize", lltostr(blksize, 10)); } } static inline void pkt_print(char *pkt, FILE *fp) { uint16_t opcode = pkt_num(pkt); size_t rem; char *opt, *val; if (!opcode || opcode > OACK) { fprintf(fp, "(%d)", opcode); } else { fprintf(fp, "%s", opcode_names[opcode - 1]); if (opcode == ACK || opcode == DATA) { fprintf(fp, "(%d)", pkt_num(pkt + 2)); } else if (opcode == WRQ || opcode == RRQ) { fprintf(fp, "(%s, %s)", pkt + 2, pkt + 2 + strlen(pkt + 2) + 1); } else if (opcode == OACK) { fprintf(fp, "("); rem = 512; pkt += 2; while (pkt_nextopt(&pkt, &opt, &val, &rem)) { fprintf(fp, " %s=%s ", opt, val); } fprintf(fp, ")"); } } } static ssize_t tftp_recvfrom(int sock, char *pkt, uint16_t* port, unsigned timeout, size_t pktlen) { ssize_t len; struct sockaddr_in src; #ifndef NMRPFLASH_WINDOWS socklen_t alen; #else int alen; #endif len = select_fd(sock, timeout); if (len < 0) { return -1; } else if (!len) { return 0; } alen = sizeof(src); len = recvfrom(sock, pkt, pktlen, 0, (struct sockaddr*)&src, &alen); if (len < 0) { sock_perror("recvfrom"); return -1; } *port = ntohs(src.sin_port); uint16_t opcode = pkt_num(pkt); if (opcode == ERR) { fprintf(stderr, "Error (%d): %.511s\n", pkt_num(pkt + 2), pkt + 4); return -1; } else if (isprint(pkt[0])) { /* In case of a firmware checksum error, the EX2700 I've tested this * on sends a raw UDP packet containing just an error message starting * at offset 0. The limit of 32 chars is arbitrary. */ fprintf(stderr, "Error: %.32s\n", pkt); return -2; } else if (!opcode || opcode > OACK) { fprintf(stderr, "Received invalid packet: "); pkt_print(pkt, stderr); fprintf(stderr, ".\n"); return -1; } if (verbosity > 2) { printf(">> "); pkt_print(pkt, stdout); printf("\n"); } return len; } static ssize_t tftp_sendto(int sock, char *pkt, size_t len, struct sockaddr_in *dst) { ssize_t sent; switch (pkt_num(pkt)) { case RRQ: case WRQ: case OACK: len = pkt_xrqlen(pkt); break; case DATA: len += 4; break; case ACK: len = 4; break; case ERR: len = 4 + strlen(pkt + 4); break; default: fprintf(stderr, "Attempted to send invalid packet "); pkt_print(pkt, stderr); fprintf(stderr, "; this is a bug!\n"); return -1; } if (verbosity > 2) { printf("<< "); pkt_print(pkt, stdout); printf("\n"); } sent = sendto(sock, pkt, len, 0, (struct sockaddr*)dst, sizeof(*dst)); if (sent < 0) { sock_perror("sendto"); } return sent; } const char *leafname(const char *path) { if (!path) { return NULL; } const char *slash, *bslash; slash = strrchr(path, '/'); bslash = strrchr(path, '\\'); if (slash && bslash) { path = 1 + (slash > bslash ? slash : bslash); } else if (slash) { path = 1 + slash; } else if (bslash) { path = 1 + bslash; } return path; } #ifdef NMRPFLASH_WINDOWS void sock_perror(const char *msg) { win_perror2(msg, WSAGetLastError()); } #endif inline bool tftp_is_valid_filename(const char *filename) { return strlen(filename) <= 255 && is_netascii(filename); } static const char *spinner = "\\|/-"; int tftp_put(struct nmrpd_args *args) { struct sockaddr_in addr; uint16_t block, port, op, blksize; ssize_t len, last_len; int fd, sock, ret, timeouts, errors, ackblock; char rx[2048], tx[2048]; const char *file_remote = args->file_remote; char *val, *end; bool rollover; const unsigned rx_timeout = MAX(args->rx_timeout / (args->blind ? 50 : 5), 2000); const unsigned max_timeouts = args->blind ? 3 : 5; sock = -1; ret = -1; fd = -1; if (g_interrupted) { goto cleanup; } if (!strcmp(args->file_local, "-")) { fd = STDIN_FILENO; if (!file_remote) { file_remote = "firmware"; } } else { fd = open(args->file_local, O_RDONLY | O_BINARY); if (fd < 0) { xperror("open"); ret = fd; goto cleanup; } else if (!file_remote) { file_remote = args->file_local; } } sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sock < 0) { sock_perror("socket"); ret = sock; goto cleanup; } memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; if (args->ipaddr_intf) { if ((addr.sin_addr.s_addr = inet_addr(args->ipaddr_intf)) == INADDR_NONE) { xperror("inet_addr"); goto cleanup; } if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) != 0) { sock_perror("bind"); goto cleanup; } } if ((addr.sin_addr.s_addr = inet_addr(args->ipaddr)) == INADDR_NONE) { xperror("inet_addr"); goto cleanup; } addr.sin_port = htons(args->port); blksize = 512; block = 0; last_len = -1; len = 0; errors = 0; rollover = false; /* Not really, but this way the loop sends our WRQ before receiving */ timeouts = 1; pkt_mkwrq(tx, file_remote, TFTP_BLKSIZE); while (!g_interrupted) { ackblock = -1; op = pkt_num(rx); if (!timeouts) { if (op == ACK) { ackblock = pkt_num(rx + 2); } else if (op == OACK) { ackblock = 0; if ((val = pkt_optval(rx, "blksize"))) { blksize = strtol(val, &end, 10); if (*end != '\0' || blksize < 8 || blksize > TFTP_BLKSIZE) { fprintf(stderr, "Error: invalid blksize in OACK: %s\n", val); ret = -1; goto cleanup; } if (verbosity) { printf("Remote accepted blksize option: %d b\n", blksize); } } } } if (timeouts || ackblock == block) { if (!timeouts) { if (++block == 0) { if (!rollover) { printf("Warning: TFTP block rollover. Upload might fail!\n"); rollover = true; } } printf("%c ", spinner[block & 3]); fflush(stdout); printf("\b\b"); pkt_mknum(tx, DATA); pkt_mknum(tx + 2, block); len = read(fd, tx + 4, blksize); if (len < 0) { xperror("read"); ret = len; goto cleanup; } else if (!len) { if (last_len != blksize && last_len != -1) { break; } } last_len = len; } ret = tftp_sendto(sock, tx, len, &addr); if (ret < 0) { goto cleanup; } } else if ((op != OACK && op != ACK) || ackblock > block) { if (verbosity) { fprintf(stderr, "Expected ACK(%d), got ", block); pkt_print(rx, stderr); fprintf(stderr, ".\n"); } if (ackblock != -1 && ++errors > 5) { fprintf(stderr, "Protocol error; bailing out.\n"); ret = -1; goto cleanup; } } ret = tftp_recvfrom(sock, rx, &port, rx_timeout, blksize + 4); if (ret < 0) { goto cleanup; } else if (!ret) { if (++timeouts < max_timeouts || (!block && timeouts < (max_timeouts * 4))) { continue; } else if (args->blind) { timeouts = 0; // fake an ACK packet pkt_mknum(rx, ACK); pkt_mknum(rx + 2, block); continue; } else if (block) { fprintf(stderr, "Timeout while waiting for ACK(%d).\n", block); } else { fprintf(stderr, "Timeout while waiting for ACK(0)/OACK.\n"); } ret = -1; goto cleanup; } else { timeouts = 0; ret = 0; if (!block && port != args->port) { if (verbosity > 1) { printf("Switching to port %d\n", port); } addr.sin_port = htons(port); } } } ret = !g_interrupted ? 0 : -1; cleanup: if (fd >= 0) { close(fd); } if (sock >= 0) { #ifndef NMRPFLASH_WINDOWS shutdown(sock, SHUT_RDWR); close(sock); #else shutdown(sock, SD_BOTH); closesocket(sock); #endif } return ret; } nmrpflash-0.9.14-16-ge95526d/util.c000066400000000000000000000035131363050564700163270ustar00rootroot00000000000000/** * nmrpflash - Netgear Unbrick Utility * Copyright (C) 2016 Joseph Lehner * * nmrpflash is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * nmrpflash is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with nmrpflash. If not, see . * */ #include #include #include #include #include "nmrpd.h" #ifdef NMRPFLASH_OSX #include #endif volatile sig_atomic_t g_interrupted = 0; time_t time_monotonic() { #ifndef NMRPFLASH_WINDOWS #ifndef NMRPFLASH_OSX struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return ts.tv_sec; #else static double factor = 0.0; mach_timebase_info_data_t timebase; if (factor == 0.0) { mach_timebase_info(&timebase); factor = (double)timebase.numer / timebase.denom; } return round(mach_absolute_time() * factor / 1e9); #endif #else return round(GetTickCount() / 1000.0); #endif } char *lltostr(long long ll, int base) { static char buf[32]; snprintf(buf, sizeof(buf) - 1, (base == 16 ? "%llx" : (base == 8 ? "%llo" : "%lld")), ll); return buf; } uint32_t bitcount(uint32_t n) { uint32_t c; for (c = 0; n; ++c) { n &= n - 1; } return c; } uint32_t netmask(uint32_t count) { return htonl(count <= 32 ? 0xffffffff << (32 - count) : 0); } void xperror(const char *msg) { if (errno != EINTR) { perror(msg); } else { printf("\n"); } } nmrpflash-0.9.14-16-ge95526d/wireshark-nmrp.lua000066400000000000000000000061201363050564700206570ustar00rootroot00000000000000-- -- NMRP dissector for Wireshark -- -- Copyright (C) 2016 Joseph C. Lehner -- -- Licensed under the GNU GPL 3.0 -- nmrp_proto = Proto("nmrp", "NMRP") src_f = ProtoField.string("nmrp.src", "Source") dst_f = ProtoField.string("nmrp.dst", "Destination") code_f = ProtoField.uint8("nmrp.code", "Code", base.HEX) id_f = ProtoField.uint8("nmrp.id", "ID", base.HEX) reserved_f = ProtoField.uint16("nmrp.reserved", "Reserved", base.HEX) len_f = ProtoField.uint16("nmrp.len", "Length") data_f = ProtoField.bytes("nmrp.opt", "Options") opt_type_f = ProtoField.uint16("nmrp.opt.type", "Option", base.HEX) opt_len_f = ProtoField.uint16("nmrp.opt.len", "Length") opt_data_f = ProtoField.bytes("nmrp.opt.data", "Data") nmrp_proto.fields = { code_f, reserved_f, len_f, data_f, id_f, opt_type_f, opt_len_f, opt_data_f } function nmrp_code(code) if code == 1 then return { "ADVERTISE", "Advertise" } elseif code == 2 then return { "CONF_REQ", "Configuration Request" } elseif code == 3 then return { "CONF_ACK", "Configuration" } elseif code == 4 then return { "CLOSE_REQ", "Close Request" } elseif code == 5 then return { "CLOSE_ACK", "Close Acknowledgement" } elseif code == 6 then return { "KEEP_ALIVE_REQ", "Keep-alive Request" } elseif code == 7 then return { "KEEP_ALIVE_ACK", "Keep-alive Acknowledgement" } elseif code == 16 then return { "TFTP_UL_REQ", "Upload Request" } else return { "#" .. code, "Unknown Opcode " .. code } end end function nmrp_opt(opt) if opt == 0x01 then return "Magic" elseif opt == 0x02 then return "IP Configuration" elseif opt == 0x04 then return "Region" elseif opt == 0x0101 then return "Update Firmware" elseif opt == 0x0102 then return "Update String Table" elseif opt == 0x0181 then return "Filename" else return "#" .. opt end end function nmrp_dissect_opt(opt, buffer, tree) if buffer:len() <= 4 then return end tree:add(opt_len_f, buffer(2, 2)) if opt == 0x01 or opt == 0x0181 then tree:add(buffer(4), "Value: " .. buffer(4):string()) elseif opt == 0x02 then tree:add(buffer(4, 4), "Address: " .. tostring(buffer(4, 4):ipv4())) tree:add(buffer(8, 4), "Netmask: " .. tostring(buffer(8, 4):ipv4())) else tree:add(opt_data_f, buffer(4, buffer:len() - 4)) end end function nmrp_proto.dissector(buffer, pinfo, tree) pinfo.cols.protocol = "NMRP" local code = buffer(2, 1) local len = buffer(4, 2) pinfo.cols.info = nmrp_code(code:uint())[2] local subtree = tree:add(nmrp_proto, buffer(0)) subtree:add(code_f, code):append_text(" - " .. nmrp_code(code:uint())[2]) subtree:add(id_f, buffer(3, 1)) subtree:add(len_f, len) subtree:add(reserved_f, buffer(0, 2)) local databuf = buffer(6, len:uint() - 6) while databuf:len() > 0 do local opt = databuf(0, 2):uint() local optlen = databuf(2, 2):uint() if databuf:len() < optlen then break end local optitem = subtree:add(opt_type_f, databuf(0, 2)):append_text(" - " .. nmrp_opt(opt)) nmrp_dissect_opt(opt, databuf(0, optlen), optitem) if databuf:len() > optlen then databuf = databuf(optlen) else break end end end eth_table = DissectorTable.get("ethertype") eth_table:add(0x0912, nmrp_proto)