[
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The licenses for most software are designed to take away your\nfreedom to share and change it.  By contrast, the GNU General Public\nLicense is intended to guarantee your freedom to share and change free\nsoftware--to make sure the software is free for all its users.  This\nGeneral Public License applies to most of the Free Software\nFoundation's software and to any other program whose authors commit to\nusing it.  (Some other Free Software Foundation software is covered by\nthe GNU Lesser General Public License instead.)  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthis service if you wish), that you receive source code or can get it\nif you want it, that you can change the software or use pieces of it\nin new free programs; and that you know you can do these things.\n\n  To protect your rights, we need to make restrictions that forbid\nanyone to deny you these rights or to ask you to surrender the rights.\nThese restrictions translate to certain responsibilities for you if you\ndistribute copies of the software, or if you modify it.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must give the recipients all the rights that\nyou have.  You must make sure that they, too, receive or can get the\nsource code.  And you must show them these terms so they know their\nrights.\n\n  We protect your rights with two steps: (1) copyright the software, and\n(2) offer you this license which gives you legal permission to copy,\ndistribute and/or modify the software.\n\n  Also, for each author's protection and ours, we want to make certain\nthat everyone understands that there is no warranty for this free\nsoftware.  If the software is modified by someone else and passed on, we\nwant its recipients to know that what they have is not the original, so\nthat any problems introduced by others will not reflect on the original\nauthors' reputations.\n\n  Finally, any free program is threatened constantly by software\npatents.  We wish to avoid the danger that redistributors of a free\nprogram will individually obtain patent licenses, in effect making the\nprogram proprietary.  To prevent this, we have made it clear that any\npatent must be licensed for everyone's free use or not licensed at all.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                    GNU GENERAL PUBLIC LICENSE\n   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n  0. This License applies to any program or other work which contains\na notice placed by the copyright holder saying it may be distributed\nunder the terms of this General Public License.  The \"Program\", below,\nrefers to any such program or work, and a \"work based on the Program\"\nmeans either the Program or any derivative work under copyright law:\nthat is to say, a work containing the Program or a portion of it,\neither verbatim or with modifications and/or translated into another\nlanguage.  (Hereinafter, translation is included without limitation in\nthe term \"modification\".)  Each licensee is addressed as \"you\".\n\nActivities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope.  The act of\nrunning the Program is not restricted, and the output from the Program\nis covered only if its contents constitute a work based on the\nProgram (independent of having been made by running the Program).\nWhether that is true depends on what the Program does.\n\n  1. You may copy and distribute verbatim copies of the Program's\nsource code as you receive it, in any medium, provided that you\nconspicuously and appropriately publish on each copy an appropriate\ncopyright notice and disclaimer of warranty; keep intact all the\nnotices that refer to this License and to the absence of any warranty;\nand give any other recipients of the Program a copy of this License\nalong with the Program.\n\nYou may charge a fee for the physical act of transferring a copy, and\nyou may at your option offer warranty protection in exchange for a fee.\n\n  2. You may modify your copy or copies of the Program or any portion\nof it, thus forming a work based on the Program, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n    a) You must cause the modified files to carry prominent notices\n    stating that you changed the files and the date of any change.\n\n    b) You must cause any work that you distribute or publish, that in\n    whole or in part contains or is derived from the Program or any\n    part thereof, to be licensed as a whole at no charge to all third\n    parties under the terms of this License.\n\n    c) If the modified program normally reads commands interactively\n    when run, you must cause it, when started running for such\n    interactive use in the most ordinary way, to print or display an\n    announcement including an appropriate copyright notice and a\n    notice that there is no warranty (or else, saying that you provide\n    a warranty) and that users may redistribute the program under\n    these conditions, and telling the user how to view a copy of this\n    License.  (Exception: if the Program itself is interactive but\n    does not normally print such an announcement, your work based on\n    the Program is not required to print an announcement.)\n\nThese requirements apply to the modified work as a whole.  If\nidentifiable sections of that work are not derived from the Program,\nand can be reasonably considered independent and separate works in\nthemselves, then this License, and its terms, do not apply to those\nsections when you distribute them as separate works.  But when you\ndistribute the same sections as part of a whole which is a work based\non the Program, the distribution of the whole must be on the terms of\nthis License, whose permissions for other licensees extend to the\nentire whole, and thus to each and every part regardless of who wrote it.\n\nThus, it is not the intent of this section to claim rights or contest\nyour rights to work written entirely by you; rather, the intent is to\nexercise the right to control the distribution of derivative or\ncollective works based on the Program.\n\nIn addition, mere aggregation of another work not based on the Program\nwith the Program (or with a work based on the Program) on a volume of\na storage or distribution medium does not bring the other work under\nthe scope of this License.\n\n  3. You may copy and distribute the Program (or a work based on it,\nunder Section 2) in object code or executable form under the terms of\nSections 1 and 2 above provided that you also do one of the following:\n\n    a) Accompany it with the complete corresponding machine-readable\n    source code, which must be distributed under the terms of Sections\n    1 and 2 above on a medium customarily used for software interchange; or,\n\n    b) Accompany it with a written offer, valid for at least three\n    years, to give any third party, for a charge no more than your\n    cost of physically performing source distribution, a complete\n    machine-readable copy of the corresponding source code, to be\n    distributed under the terms of Sections 1 and 2 above on a medium\n    customarily used for software interchange; or,\n\n    c) Accompany it with the information you received as to the offer\n    to distribute corresponding source code.  (This alternative is\n    allowed only for noncommercial distribution and only if you\n    received the program in object code or executable form with such\n    an offer, in accord with Subsection b above.)\n\nThe source code for a work means the preferred form of the work for\nmaking modifications to it.  For an executable work, complete source\ncode means all the source code for all modules it contains, plus any\nassociated interface definition files, plus the scripts used to\ncontrol compilation and installation of the executable.  However, as a\nspecial exception, the source code distributed need not include\nanything that is normally distributed (in either source or binary\nform) with the major components (compiler, kernel, and so on) of the\noperating system on which the executable runs, unless that component\nitself accompanies the executable.\n\nIf distribution of executable or object code is made by offering\naccess to copy from a designated place, then offering equivalent\naccess to copy the source code from the same place counts as\ndistribution of the source code, even though third parties are not\ncompelled to copy the source along with the object code.\n\n  4. You may not copy, modify, sublicense, or distribute the Program\nexcept as expressly provided under this License.  Any attempt\notherwise to copy, modify, sublicense or distribute the Program is\nvoid, and will automatically terminate your rights under this License.\nHowever, parties who have received copies, or rights, from you under\nthis License will not have their licenses terminated so long as such\nparties remain in full compliance.\n\n  5. You are not required to accept this License, since you have not\nsigned it.  However, nothing else grants you permission to modify or\ndistribute the Program or its derivative works.  These actions are\nprohibited by law if you do not accept this License.  Therefore, by\nmodifying or distributing the Program (or any work based on the\nProgram), you indicate your acceptance of this License to do so, and\nall its terms and conditions for copying, distributing or modifying\nthe Program or works based on it.\n\n  6. Each time you redistribute the Program (or any work based on the\nProgram), the recipient automatically receives a license from the\noriginal licensor to copy, distribute or modify the Program subject to\nthese terms and conditions.  You may not impose any further\nrestrictions on the recipients' exercise of the rights granted herein.\nYou are not responsible for enforcing compliance by third parties to\nthis License.\n\n  7. If, as a consequence of a court judgment or allegation of patent\ninfringement or for any other reason (not limited to patent issues),\nconditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot\ndistribute so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you\nmay not distribute the Program at all.  For example, if a patent\nlicense would not permit royalty-free redistribution of the Program by\nall those who receive copies directly or indirectly through you, then\nthe only way you could satisfy both it and this License would be to\nrefrain entirely from distribution of the Program.\n\nIf any portion of this section is held invalid or unenforceable under\nany particular circumstance, the balance of the section is intended to\napply and the section as a whole is intended to apply in other\ncircumstances.\n\nIt is not the purpose of this section to induce you to infringe any\npatents or other property right claims or to contest validity of any\nsuch claims; this section has the sole purpose of protecting the\nintegrity of the free software distribution system, which is\nimplemented by public license practices.  Many people have made\ngenerous contributions to the wide range of software distributed\nthrough that system in reliance on consistent application of that\nsystem; it is up to the author/donor to decide if he or she is willing\nto distribute software through any other system and a licensee cannot\nimpose that choice.\n\nThis section is intended to make thoroughly clear what is believed to\nbe a consequence of the rest of this License.\n\n  8. If the distribution and/or use of the Program is restricted in\ncertain countries either by patents or by copyrighted interfaces, the\noriginal copyright holder who places the Program under this License\nmay add an explicit geographical distribution limitation excluding\nthose countries, so that distribution is permitted only in or among\ncountries not thus excluded.  In such case, this License incorporates\nthe limitation as if written in the body of this License.\n\n  9. The Free Software Foundation may publish revised and/or new versions\nof the General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number.  If the Program\nspecifies a version number of this License which applies to it and \"any\nlater version\", you have the option of following the terms and conditions\neither of that version or of any later version published by the Free\nSoftware Foundation.  If the Program does not specify a version number of\nthis License, you may choose any version ever published by the Free Software\nFoundation.\n\n  10. If you wish to incorporate parts of the Program into other free\nprograms whose distribution conditions are different, write to the author\nto ask for permission.  For software which is copyrighted by the Free\nSoftware Foundation, write to the Free Software Foundation; we sometimes\nmake exceptions for this.  Our decision will be guided by the two goals\nof preserving the free status of all derivatives of our free software and\nof promoting the sharing and reuse of software generally.\n\n                            NO WARRANTY\n\n  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\nFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\nOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\nPROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\nOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\nTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\nPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\nREPAIR OR CORRECTION.\n\n  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\nREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\nOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\nTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\nYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\nPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGES.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nconvey the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {description}\n    Copyright (C) {year}  {fullname}\n\n    This program is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License along\n    with this program; if not, write to the Free Software Foundation, Inc.,\n    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf the program is interactive, make it output a short notice like this\nwhen it starts in an interactive mode:\n\n    Gnomovision version 69, Copyright (C) year name of author\n    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, the commands you use may\nbe called something other than `show w' and `show c'; they could even be\nmouse-clicks or menu items--whatever suits your program.\n\nYou should also get your employer (if you work as a programmer) or your\nschool, if any, to sign a \"copyright disclaimer\" for the program, if\nnecessary.  Here is a sample; alter the names:\n\n  Yoyodyne, Inc., hereby disclaims all copyright interest in the program\n  `Gnomovision' (which makes passes at compilers) written by James Hacker.\n\n  {signature of Ty Coon}, 1 April 1989\n  Ty Coon, President of Vice\n\nThis General Public License does not permit incorporating your program into\nproprietary programs.  If your program is a subroutine library, you may\nconsider it more useful to permit linking proprietary applications with the\nlibrary.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.\n\n"
  },
  {
    "path": "Makefile",
    "content": "C=gcc\n\nall: uds-server\n\nuds-userver: uds-server.o\n\t$(CC) -o uds-server uds-server.c\n\nclean:\n\trm -f uds-server *.o\n"
  },
  {
    "path": "README.md",
    "content": "UDS Server\n==========\n\nUnified Diagnostic Services (UDS) Server - is a ECU simulator that provides UDS support.\nThis application was originally written to go alongside of [ICSim] (https://github.com/zombieCraig/ICSim)\nfor training.\n\nRunning both ICSim and uds-server can give students a more realistic use of tools.  You can use\nICSim to understand the basics of reversing CAN and uds-server to dig into the UDS protocol\nand Engine Control Unit (ECU) inspections such as memory reads and device I/O controls via the ECU instead of spoofed\nController Area Network (CAN bus) packets.\n\nIn addition, when developing uds-server, it showed several more uses.  When a dealership tool\nis known to uds-server, it makes it very easy to see what the tool is attempting to do by spoofing\na real target vehicle.  This allows you to quickly reverse commands from dealership tools and\nsee only the packets that matter.  Another nice feature, is the ability to fuzz the\ndealership/scantools to see if they are doing proper input validation checks.  This enables\nuds-server to work as a security tool by playing the role of a modified \"malicious\" vehicle and\nseeing how the shop's tools handle the malformed requests.\n\n\nCompiling uds-server\n====================\n\nRight now the tool was developed on Ubuntu Linux but is simple enough that it should compile on\nany standard Linux system.  Simply type 'make':\n\n```\n$ make\ncc     uds-server.c   -o uds-server\n```\n\nThis version is still considered 'alpha' but the help screen should look something like:\n\n```\nSimulates UDS responses\nUsage: ./uds-server [options] <can_interface>\n\t-z\t\tIncrease fuzz level\n\t-v\t\tVerbose\n\t-l <logfile>\tLog output to file instead of STDOUT\n\t-c\t\tDon't fuzz ISOTP Spec, just data\n\t-F\t\tDisable flow control (Functional Addressing)\n\t-V <vin>\tSpecify VIN (Default: WAUZZZ8V9FA149850)\n```\n\nMost of these switches are just for early testing and will eventually be moved\nto a config file for more flexibility in fuzzing, etc.\n\nRunning uds-server for testing\n==============================\n\nIf you are running uds-server along with ICSim then simply start another terminal window and\nrun:d\n\n```\n$ uds-server vcan0\n```\n\nThen you can practice commands to get VIN or use things like [CaringCaribou] (https://github.com/CaringCaribou/caringcaribou) to brute force or identify diagnostic services.\n\nIf you ware working with a dealership tool or a scan tool then you will use the real can0 interface\ninstead.  You will need a small CAN network to bridge the dealership/scantool with your CAN\nsniffer attached to uds-server.  You can breadboard this or build a small portable device we lovingly\ncall the ODB GW.\n\n\nODB GW\n======\n\nThe ODB Gateway (ODB GW) is a tribute to Ol' Dirty Bastard (RIP) and the mispronunciation \nof OBD (On-board diagnostics) ports.  It is a simple device that you can easily build yourself:\n\n* 2 x Female J1962 OBD-II Ports (~$10/ea)\n* Project Box (~$5)\n* at least 2 120 Ohm Resistors (or 1 240 Ohm) (pennies)\n* 12 V Power Supply (~12)\n* Some wires and maybe banana plug connectors\n\nThe minimum wiring is as follows:\n\n* Connect pin 12 together for power and splice a line to the 12V supply\n* Connect pins 4 and 5 together for ground and splice a line to the 12V supply\n* Connect pin 6 together for CAN High\n* Connect pin 14 together for CAN Low\n* Add 240 Ohm resistance across CAN High and Low\n\nYou can bridge more pins but how they are wired depends on what type of vehicle scanner you\nare testing.  For instance, several vehicles have many different CAN buses on the other\navailable pins while other manufacturers use the other pins for different protocols such\nas K-Line/KWP.  The above wiring is universal but you may miss out on signals from\ndealership tools if you don't also listen on the other pins.\n\nReversing Dealership Tools\n==========================\n\nUsing your own CAN network or the ODB GW, plug in a dealership tool or scan tool in one end and \nyour sniffer on the other.  Make sure 12V power is supplied to your virtual bus, some scantools\nonly operate when they have power from pin 16.  Set your CAN bus speeds to be the speed\nthe dealership tool will expect, for HS CAN this is most likely 500k.\n\n```\n$ sudo ip link set can0 up type can bitrate 500000\n```\n\nNow run uds-server with the verbose option set on your can0 interface and use the\ndealership tool like you would on an actual vehicle.  For example below we use a GM TechII\nand request the doors to unlock via the TechII interface.  Looking at the uds-server output\nwe see:\n\n```\nPkt: 244#01 3E \nResponding with a generic OK message\nPkt: 244#04 AA 03 02 07 \nReceived GM Read Data by ID Request\n + Medium Rate\nPkt: 244#01 3E \nResponding with a generic OK message\nPkt: 244#07 AE 01 03 00 00 00 00 \nUnhandled mode/sid: Device Control (GM)\nPkt: 244#01 3E \nResponding with a generic OK message\nPkt: 101#FE 01 3E 55 55 55 55 55 \nPkt: 244#01 3E \nResponding with a generic OK message\nPkt: 244#02 AE 00 \nUnhandled mode/sid: Device Control (GM)\nPkt: 244#01 3E \nResponding with a generic OK message\nPkt: 244#01 3E \nResponding with a generic OK message\nPkt: 244#02 AA 00 \nReceived GM Read Data by ID Request\n + Stop Data Request\n```\n\nIn this output the generic OK message refers to a TesterPresent packet sent by the dealership\ntool.  We simply respond with OK when we see things like this.  Next the Tool requests some\ndata to be sent at a Medium interval rate.  uds-server will do that with bogus data.  Then we see\na Device Control (GM) request.  We don't handle it because it's an output request and there is\nnothing to spoof.  However the packet info is useful:\n\n```\nPkt: 244#07 AE 01 03 00 00 00 00\nUnhandled mode/sid: Device Control (GM)\n```\n\nThis means that sending 244#07AE010300000000 after sending TesterPresent (244#013E) will unlock\nthe driver side door.  Later there is another Device Control message to stop doing device\ncontrols 244#02AE00.\n\nThis makes it very easy to identify IO controls and to see where data is being requested from.\nOften dealership tools won't use the standard UDS mode $09 to get things like VIN but instead they\nrequest VIN and other information via memory locations.\n\nFuzzing Dealership Tools\n========================\n\nIf you want to test the security of a dealership tool or scantool then uds-server has a fuzzing\noption.  Currently this is still in a Proof of Concept (PoC) stage and it needs to be refined but\nthe way it currently works is you can specify -z to increase the fuzzing level.  The more -z's you\nuse the more fuzzing it will do.\n\nFor instance:\n\n```\n$ uds-server -v -z can0\nUsing CAN interface can0\nFuzz level set to: 1\n```\nThis will do things like randomize the Vehicle Identification Number (VIN) and some Diagnostic \nTrouble Code (DTC) messages.\n\n```\n$ uds-server -v -zzzz can0\nUsing CAN interface can0\nFuzz level set to: 4\n```\nThis will do things like send WAY too many DTCs (think hundreds) or create HUGE VINs that\nalso include binary data.  A VIN contains an internal checksum that uds-server will automatically\ncalculate correctly for fuzzing.  If you want to specify a VIN you can do so via the command\nline:\n\n```\n$ uds-server -v -V \"PWN3D OP3N G4R4G3\" can0\n```\n\nThis will report the vehicles VIN as \"PWN3D OP3N G4R4G3\" which by the way is a \"valid\" VIN based on the\nchecksum byte.  Some tools use VIN as the lookup for what type of vehicle it is working with, so\nspecifying a valid one for your target vehicle can be useful.\n\nuds-server hacking\n==================\n\nRight now new ECU modules need to be added by hand.  Which means you will need to understand the C\ncode and add handlers for how you want to respond to different types of packets.  Debugging currently\nis a hard coded constant as well.  This is because uds-server is still in its PoC stage and could\nevolve in many different directions.\n\nFeel free to fork the code and add whatever new handlers you want to add.  Ultimately the fuzzing\nconfiguration and ECU configurations will be handled by a separate config file.\n\nCredits\n=======\nCraig Smith - craig@theialabs.com\nOpenGarages - opengarages.org (@OpenGarages)\n\n"
  },
  {
    "path": "can_setup.sh",
    "content": "sudo ip link set can0 up type can bitrate 500000\n"
  },
  {
    "path": "uds-server.c",
    "content": "/*\n * Instrument cluster simulator\n *\n * (c) 2014 Open Garages - Craig Smith <craig@theialabs.com>\n */\n\n#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <string.h>\n#include <signal.h>\n#include <getopt.h>\n#include <time.h>\n#include <sys/time.h>\n#include <sys/socket.h>\n#include <sys/ioctl.h>\n#include <sys/stat.h>\n#include <net/if.h>\n#include <linux/can.h>\n#include <linux/can/raw.h>\n\n#include \"uds-server.h\"\n\n#define DEBUG 0\n//#define VIN \"1G1ZT53826F109149\"\n//#define VIN \"5YJSA1S2FEFA00001\"\n#define VIN \"WAUZZZ8V9FA149850\"\n//#define VIN \"2B3KA43R86H389824\"\n#define DATA_ALPHA     0\n#define DATA_ALPHANUM  1\n#define DATA_BINARY    2\n\n/* Globals */\nint running = 0;\nint verbose = 0;\nint no_flow_control = 0;\nint fuzz_level = 0;\nint keep_spec = 0;\nFILE *plogfp = NULL;\nchar *vin = VIN;\nstruct timeval start_tv;\nint pending_data;\nstruct can_frame gm_data_by_id;\nlong gm_lastcms = 0;\n\n/* This is for flow control packets */\nchar gBuffer[255];\nint gBufSize;\nint gBufLengthRemaining;\nint gBufCounter;\n\n/* Prototypes */\nvoid print_pkt(struct canfd_frame);\nvoid print_bin(unsigned char *, int);\n\n\nvoid usage(char *app, char *msg) {\n  printf(\"Simulates UDS responses\\n\");\n  if (msg) printf(\"%s\\n\", msg);\n  printf(\"Usage: %s [options] <can_interface>\\n\", app);\n  printf(\"\\t-z\\t\\tIncrease fuzz level\\n\");\n  printf(\"\\t-v\\t\\tVerbose\\n\");\n  printf(\"\\t-l <logfile>\\tLog output to file instead of STDOUT\\n\");\n  printf(\"\\t-c\\t\\tDon't fuzz ISOTP Spec, just data\\n\");\n  printf(\"\\t-F\\t\\tDisable flow control (Functional Addressing)\\n\");\n  printf(\"\\t-V <vin>\\tSpecify VIN (Default: %s)\\n\", VIN);\n  printf(\"\\n\");\n  exit(1);\n}\n\n// Simple function to print logging info to screen or to a file\nvoid plog(char *fmt, ...) {\n  va_list args;\n  char buf[2046];\n  int len;\n\n  va_start(args, fmt);\n  len = vsnprintf(buf, 2045, fmt, args);\n  va_end(args);\n\n  if(plogfp) {\n    len = fwrite(buf, 1, len, plogfp);\n  } else {\n    printf(\"%s\", buf);\n  }\n}\n\nvoid intHandler(int sig) {\n    running = 0;\n}\n\n// Generates data into a buff and returns it.\nchar *gen_data(int scope, int size) {\n  char *charset, *buf;\n  unsigned char byte;\n  int num;\n  int i;\n  buf = malloc(size);\n  memset(buf,0,size);\n  switch(scope) {\n    case DATA_ALPHA:\n       charset = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n       for(i = 0; i < size; i++) {\n         buf[i] = charset[rand() % strlen(charset)];\n       } \n       break;\n    case DATA_ALPHANUM:\n       charset = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n       for(i = 0; i < size; i++) {\n         num = rand() % strlen(charset);\n         byte = charset[num];\nif (DEBUG) printf(\"DEBUG: random byte[%d] = %d %02X\\n\", i, num, byte);\n         buf[i] = byte;\n       } \n       break;\n    case DATA_BINARY:\n       for(i = 0; i < size; i++) {\n         buf[i] = rand() % 256;\n       }\n    default:\n      break;\n  }\n  return buf;\n}\n\n// If a flow control packet comes in, push out more data\n// This isn't fully supported, just a hack at the moment\nvoid flow_control_push_to(int can, int id) {\n  struct canfd_frame frame;\n  int nbytes;\n  if(no_flow_control) return;\n  if(verbose) plog(\"FC: Flushing ISOTP buffers\\n\");\n  frame.can_id = id;\n  while(gBufLengthRemaining > 0) {\n    if(gBufLengthRemaining > 7) {\n      frame.len = 8;\n      frame.data[0] = gBufCounter;\n      memcpy(&frame.data[1], gBuffer+(gBufSize-gBufLengthRemaining), 7);\n      nbytes = write(can, &frame, CAN_MTU);\n      if(nbytes < 0) perror(\"Write packet (FC)\");\n      gBufCounter++;\n      gBufLengthRemaining -= 7;\n    } else {\n      frame.len = gBufLengthRemaining + 1;\n      frame.data[0] = gBufCounter;\n      memcpy(&frame.data[1], gBuffer+(gBufSize-gBufLengthRemaining), CAN_MTU);\n      nbytes = write(can, &frame, CAN_MTU);\n      if(nbytes < 0) perror(\"Write packet (FC Final)\");\n      gBufLengthRemaining = 0;\n    }\n  }\n}\n\nvoid flow_control_push(int can) {\n  flow_control_push_to(can, 0x7e8);\n}\n\nvoid isotp_send_to(int can, char *data, int size, int dest) {\n  struct canfd_frame frame;\n  int left = size;\n  int counter;\n  int nbytes;\n  if(size > 256) return;\n  frame.can_id = dest;\n  if(size < 7) {\n    frame.len = size + 1;\n    frame.data[0] = size;\n    memcpy(&frame.data[1], data, size);\n    nbytes = write(can, &frame, CAN_MTU);\n    if(nbytes < 0) perror(\"Write packet\");\n  } else {\n    frame.len = 8;\n    frame.data[0] = 0x10;\n    if(fuzz_level > 2 && keep_spec == 0) {\n      frame.data[1] = rand() % 256;\n      printf(\"Breaking ISOTP specs real size = %d reported size = %d\\n\", size, frame.data[1]);\n    } else {\n      frame.data[1] = (char)size-1;\n    }\n    memcpy(&frame.data[2], data, 6);\n    nbytes = write(can, &frame, CAN_MTU);\n    if(nbytes < 0) perror(\"Write packet\");\n    left -= 6;\n    counter = 0x21;\n    if(no_flow_control) {\n      while(left > 0) {\n        if(left > 7) {\n          frame.len = 8;\n          frame.data[0] = counter;\n          memcpy(&frame.data[1], data+(size-left), 7);\n          write(can, &frame, CAN_MTU);\n          counter++;\n          left -= 7;\n        } else {\n          frame.len = left + 1;\n          frame.data[0] = counter;\n          memcpy(&frame.data[1], data+(size-left), CAN_MTU);\n          write(can, &frame, frame.len);\n          left = 0;\n        }\n      }\n    } else { // FC\n      memcpy(gBuffer, data, size); // Size is restricted to <256\n      gBufSize = size;\n      gBufLengthRemaining = left;\n      gBufCounter = counter;\n    }\n  }\n}\n\nvoid isotp_send(int can, char *data, int size) {\n  isotp_send_to(can, data, size, 0x7e8);\n}\n\n/*\n * Some UDS queries requiest periodic data.  This handles those\n */\nvoid handle_pending_data(int can) {\n  struct canfd_frame frame;\n  struct timeval tv;\n  long currcms;\n  int i, offset, datacnt;\n  if(!pending_data) return;\n\n  gettimeofday(&tv, NULL);\n  currcms = (tv.tv_sec - start_tv.tv_sec) * 100 + (tv.tv_usec / 10000);\n\n  if(IS_SET(pending_data, PENDING_READ_DATA_BY_ID_GM)) {\n        if(gm_data_by_id.data[0] == 0xFE) {\n          offset = 1;\n        } else {\n          offset = 0;\n        }\n        frame.can_id = gm_data_by_id.can_id;\n        frame.len = 8;\n        switch(gm_data_by_id.data[2 + offset]) { // Subfunctions\n          case 0x02:  // Slow Rate\n            if (currcms - gm_lastcms > 1000) {\n              for(i=3; i < gm_data_by_id.data[0]+1; i++) {\n                frame.data[0] = gm_data_by_id.data[i];\n                for(datacnt=1; datacnt < 8; datacnt++) {\n                  frame.data[datacnt] = rand() % 255;\n                }\n                write(can, &frame, CAN_MTU);\n                if(verbose > 1) plog(\"  + Sending GM data (%02X) at a slow rate\\n\", frame.data[0]);\n              }\n              gm_lastcms = currcms;\n            }\n            break;\n          case 0x03:  // Medium Rate\n            if (currcms - gm_lastcms > 100) {\n              for(i=3; i < gm_data_by_id.data[0]+1; i++) {\n                frame.data[0] = gm_data_by_id.data[i];\n                for(datacnt=1; datacnt < 8; datacnt++) {\n                  frame.data[datacnt] = rand() % 255;\n                }\n                write(can, &frame, CAN_MTU);\n                if(verbose > 1) plog(\"  + Sending GM data (%02X) at a medium rate\\n\", frame.data[0]);\n              }\n              gm_lastcms = currcms;\n            }\n            break;\n          case 0x04:  // Fast Rate\n            if (currcms - gm_lastcms > 20) {\n              for(i=3; i < gm_data_by_id.data[0]+1; i++) {\n                frame.data[0] = gm_data_by_id.data[i];\n                for(datacnt=1; datacnt < 8; datacnt++) {\n                  frame.data[datacnt] = rand() % 255;\n                }\n                write(can, &frame, CAN_MTU);\n                if(verbose > 1) plog(\"  + Sending GM data (%02X) at a fast rate\\n\", frame.data[0]);\n              }\n              gm_lastcms = currcms;\n            }\n            break;\n          default:\n            plog(\"Unknown subfunction timer\\n\");\n            break;\n        }\n  } // IS_SET PENDING_READ_DATA_BY_ID_GM\n}\n\nvoid send_dtcs(int can, char total, struct canfd_frame frame) {\n  char resp[1024];\n  char i;\n  memset(resp, 0, 1024);\n  switch(fuzz_level) {\n    case 0:  // Default is to make P01XX where XX = total number of DTCs\n      resp[0] = frame.data[1] + 0x40;\n      resp[1] = total; // Total DTCs\n      for(i = 0; i <= total*2; i+=2) {\n        resp[2+i] = 1;\n        resp[2+i+1] = i;\n      }\n      if(total == 0) {\n        isotp_send(can, resp, 2);\n      } else if (total < 3) {\n        isotp_send(can, resp, 2+(total*2));\n      } else {\n        isotp_send(can, resp, total*2);\n      }\n      break;\n    case 1:\n      resp[0] = frame.data[1] + 0x40;\n      resp[1] = rand() % 256;\n      if (verbose) plog(\"Randomized total DTCs to %d real DTCs %d\\n\", resp[1], total);\n      for(i = 0; i <= total*2; i+=2) {\n        resp[2+i] = 1;\n        resp[2+i+1] = i;\n      }\n      if(total == 0) {\n        isotp_send(can, resp, 2);\n      } else if (total < 3) {\n        isotp_send(can, resp, 2+(total*2));\n      } else {\n        isotp_send(can, resp, total*2);\n      }\n      break;\n    case 2:\n    default:\n      resp[0] = frame.data[1] + 0x40;\n      total = rand() % 128;\n      resp[1] = total;\n      if (verbose) plog(\"Randomized total DTCs to %d\\n\", resp[1]);\n      for(i = 0; i <= total*2; i+=2) {\n        resp[2+i] = rand() % 256;\n        resp[2+i+1] = rand() % 256;\n      }\n      if (verbose) {\n        plog(\"DTC random data is:\\n\");\n        print_bin(&resp[2], total*2);\n      }\n      if(total == 0) {\n        isotp_send(can, resp, 2);\n      } else if (total < 3) {\n        isotp_send(can, resp, 2+(total*2));\n      } else {\n        isotp_send(can, resp, total*2);\n      }\n      break;\n  }\n}\n\nunsigned char calc_vin_checksum(char *vin, int size) {\n  char w[17] = { 8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2 };\n  int i;\n  int checksum = 0;\n  int num;\n  for(i=0; i < size; i++) {\n    if(vin[i] == 'I' || vin[i] == 'O' || vin[i] == 'Q') {\n      num = 0;\n    } else {\n      if(vin[i] >= '0' && vin[i] <='9') num = vin[i] - '0';\n      if(vin[i] >= 'A' && vin[i] <='I') num = (vin[i] - 'A') + 1;\n      if(vin[i] >= 'J' && vin[i] <='R') num = (vin[i] - 'J') + 1;\n      if(vin[i] >= 'S' && vin[i] <='Z') num = (vin[i] - 'S') + 2;\n    }\n    checksum += num * w[i];\n  }\n  checksum = checksum % 11;\n  if (checksum == 10) return 'X';\n  return ('0' + checksum);\n}\n\nvoid send_error_snfs(int can, struct canfd_frame frame) {\n  char resp[4];\n  if(verbose) plog(\"Responded with Sub Function Not Supported\\n\");\n  resp[0] = 0x7f;\n  resp[1] = frame.data[1];\n  resp[2] = 12; // SubFunctionNotSupported\n  isotp_send(can, resp, 3);\n}\n\nvoid send_error_roor(int can, struct canfd_frame frame, int id) {\n  char resp[4];\n  if(verbose) plog(\"Responded with Sub Function Not Supported\\n\");\n  resp[0] = 0x7f;\n  resp[1] = frame.data[1];\n  resp[2] = 31; // RequestOutOfRange\n  isotp_send_to(can, resp, 3, id);\n}\n\nvoid generic_OK_resp(int can, struct canfd_frame frame) {\n  char resp[4];\n  if(verbose > 1) plog(\"Responding with a generic OK message\\n\");\n  resp[0] = frame.data[1] + 0x40;\n  resp[1] = frame.data[2];\n  resp[2] = 0;\n  isotp_send(can, resp, 3);\n}\n\nvoid generic_OK_resp_to(int can, struct canfd_frame frame, int id) {\n  char resp[4];\n  if(verbose > 1) plog(\"Responding with a generic OK message\\n\");\n  resp[0] = frame.data[1] + 0x40;\n  resp[1] = frame.data[2];\n  resp[2] = 0;\n  isotp_send_to(can, resp, 3, id);\n}\n\nvoid handle_current_data(int can, struct canfd_frame frame) {\n  if(verbose) plog(\"Received Current info request\\n\");\n  char resp[8];\n  switch(frame.data[2]) {\n    case 0x00: // Supported PIDs\n      if(verbose) plog(\"Responding with a generic set of PIDs (1-20)\\n\");\n      resp[0] = frame.data[1] + 0x40;\n      resp[1] = frame.data[2];\n      resp[2] = 0xBF;\n      resp[3] = 0xBF;\n      resp[4] = 0xB9;\n      resp[5] = 0x93;\n      isotp_send(can, resp, 6);\n      break;\n    case 0x01: // MIL & DTC Status\n      if(verbose) plog(\"Responding to MIL and DTC Status request\\n\");\n      resp[0] = frame.data[1] + 0x40;\n      resp[1] = frame.data[2];\n      resp[2] = 0x00;\n      resp[3] = 0x07;\n      resp[4] = 0xE5;\n      resp[5] = 0xE5;\n      isotp_send(can, resp, 6);\n      break;\n    case 0x20: // More supported PIDs (21-40)\n      if(verbose) plog(\"Responding with PIDs supported (21-40)\\n\");\n      resp[0] = frame.data[1] + 0x40;\n      resp[1] = frame.data[2];\n      resp[2] = 0xBF;\n      resp[3] = 0xBF;\n      resp[4] = 0xB9;\n      resp[5] = 0x93;\n      isotp_send(can, resp, 6);\n      break;\n    case 0x40: // More supported PIDs (41-60)\n      if(verbose) plog(\"Responding with PIDs supported (41-60)\\n\");\n      resp[0] = frame.data[1] + 0x40;\n      resp[1] = frame.data[2];\n      resp[2] = 0xBF;\n      resp[3] = 0xBF;\n      resp[4] = 0xB9;\n      resp[5] = 0x93;\n      isotp_send(can, resp, 6);\n      break;\n    case 0x41: // Monitor status this drive cycle\n      resp[0] = frame.data[1] + 0x40;\n      resp[1] = frame.data[2];\n      resp[2] = 0;\n      resp[3] = 0x0F;\n      resp[4] = 0xFF;\n      resp[5] = 0x00;\n      isotp_send(can, resp, 6);\n      break;\n    case 0x60: // More supported PIDs (61-80)\n      if(verbose) plog(\"Responding with PIDs supported (61-80)\\n\");\n      resp[0] = frame.data[1] + 0x40;\n      resp[1] = frame.data[2];\n      resp[2] = 0xBF;\n      resp[3] = 0xBF;\n      resp[4] = 0xB9;\n      resp[5] = 0x93;\n      isotp_send(can, resp, 6);\n      break;\n    case 0x80: // More supported PIDs (81-100)\n      if(verbose) plog(\"Responding with PIDs supported (81-100)\\n\");\n      resp[0] = frame.data[1] + 0x40;\n      resp[1] = frame.data[2];\n      resp[2] = 0xBF;\n      resp[3] = 0xBF;\n      resp[4] = 0xB9;\n      resp[5] = 0x93;\n      isotp_send(can, resp, 6);\n      break;\n    case 0xA0:  // More Supported PIDs (101-120)\n      if(verbose) plog(\"Responding with PIDs supported (101-120)\\n\");\n      resp[0] = frame.data[1] + 0x40;\n      resp[1] = frame.data[2];\n      resp[2] = 0xBF;\n      resp[3] = 0xBF;\n      resp[4] = 0xB9;\n      resp[5] = 0x93;\n      isotp_send(can, resp, 6);\n      break;\n    case 0xC0: // More supported PIDs (121-140)\n      if(verbose) plog(\"Responding with PIDs supported (121-140)\\n\");\n      resp[0] = frame.data[1] + 0x40;\n      resp[1] = frame.data[2];\n      resp[2] = 0xBF;\n      resp[3] = 0xBF;\n      resp[4] = 0xB9;\n      resp[5] = 0x93;\n      isotp_send(can, resp, 6);\n      break;\n    default:\n      if(verbose) plog(\"Note: Requested unsupported service %02X\\n\", frame.data[2]);\n      break;\n  }\n}\n\nvoid handle_vehicle_info(int can, struct canfd_frame frame) {\n  char *buf;\n  int pktsize = 0;\n  unsigned char chksum;\n  if(verbose) plog(\"Received Vehicle info request\\n\");\n  char resp[300];\n  switch(frame.data[2]) {\n    case 0x00: // Supported PIDs\n      if(verbose) plog(\"Replying with ALL Pids supported\\n\");\n      resp[0] = frame.data[1] + 0x40;\n      resp[1] = frame.data[2];\n      resp[2] = 0x55;\n      resp[3] = 0;\n      resp[4] = 0;\n      resp[5] = 0;\n      isotp_send(can, resp, 6);\n      break;\n    case 0x02: // Get VIN\n      switch(fuzz_level) {\n        case 0:\n          if(verbose) plog(\"Sending VIN %s\\n\", vin);\n          resp[0] = frame.data[1] + 0x40;\n          resp[1] = frame.data[2];\n          resp[2] = 1;\n          memcpy(&resp[3], vin, strlen(vin));\n          isotp_send(can, resp, 4 + strlen(vin));\n          break;\n        case 1:\n          if(verbose) plog(\"Fuzzing VIN with printable chars\\n\");\n          resp[0] = frame.data[1] + 0x40;\n          resp[1] = frame.data[2];\n          resp[2] = 1;\n          buf = gen_data(DATA_ALPHANUM, 17);\n          chksum = calc_vin_checksum(buf, 17);\n          buf[8] = chksum;\n          if(verbose) plog(\"Using VIN: %s\\n\", buf);\n          memcpy(&resp[3], buf, 17);\n          free(buf);\n          isotp_send(can, resp, 4 + 17);\n          break;\n        case 2:\n        case 3:  // At 3 the ISOTP spec gets flaky\n          pktsize = rand() % 252;\n          if(verbose) plog(\"Fuzzing big VIN with printable chars\\n\");\n          resp[0] = frame.data[1] + 0x40;\n          resp[1] = frame.data[2];\n          resp[2] = 1;\n          buf = gen_data(DATA_ALPHANUM, pktsize);\n          chksum = calc_vin_checksum(buf, pktsize);\n          buf[8] = chksum;\n          if(verbose) plog(\"Using big VIN (%d chars): %s\\n\",pktsize, buf);\n          memcpy(&resp[3], buf, pktsize);\n          free(buf);\n          isotp_send(can, resp, 4 + pktsize);\n          break;\n        case 4:\n          if(verbose) plog(\"Fuzzing VIN with binary data\\n\");\n          resp[0] = frame.data[1] + 0x40;\n          resp[1] = frame.data[2];\n          resp[2] = 1;\n          buf = gen_data(DATA_BINARY, 17);\n          chksum = calc_vin_checksum(buf, 17);\n          buf[8] = chksum;\n          if(verbose) print_bin(buf, 17);\n          memcpy(&resp[3], buf, 17);\n          free(buf);\n          isotp_send(can, resp, 4 + 17);\n          break;\n        case 5:\n        default:\n          pktsize = rand() % 252;\n          if(verbose) plog(\"Fuzzing VIN with binary data with size %d\\n\", pktsize);\n          resp[0] = frame.data[1] + 0x40;\n          resp[1] = frame.data[2];\n          resp[2] = 1;\n          buf = gen_data(DATA_BINARY, pktsize);\n          if(verbose) print_bin(buf, pktsize);\n          memcpy(&resp[3], buf, pktsize);\n          free(buf);\n          isotp_send(can, resp, 4 + pktsize);\n          break;\n      }\n      break;\n    default:\n      break;\n  }\n}\n\nvoid handle_pending_codes(int can, struct canfd_frame frame) {\n  if(verbose) plog(\"Received request for pending trouble codes\\n\");\n  send_dtcs(can, 20, frame);\n}\n\nvoid handle_stored_codes(int can, struct canfd_frame frame) {\n  if(verbose) plog(\"Received request for stored trouble codes\\n\");\n  send_dtcs(can, 2, frame);\n}\n\n// TODO: This is wrong.  Record a real transaction to see the format\nvoid handle_freeze_frame(int can, struct canfd_frame frame) {\n  if(verbose) plog(\"Received request for freeze frame code\\n\");\n  //send_dtcs(can, 1, frame);\n  char resp[4];\n  resp[0] = frame.data[1] + 0x40;\n  resp[1] = 0x01;\n  resp[2] = 0x01;\n  isotp_send(can, resp, 3);\n}\n\nvoid handle_perm_codes(int can, struct canfd_frame frame) {\n  if(verbose) plog(\"Received request for permanent trouble codes\\n\");\n  send_dtcs(can, 0, frame);\n}\n\nvoid handle_dsc(int can, struct canfd_frame frame) {\n  //if(verbose) plog(\"Received DSC Request\\n\");\n  //send_error_snfs(can, frame);\n  if(verbose) plog(\"Received DSC Request giving VCDS respose\\n\");\n      frame.can_id = 0x77A;\n      frame.len = 8;\n      frame.data[0] = 0x06;\n      frame.data[1] = 0x50;\n      frame.data[2] = 0x03;\n      frame.data[3] = 0x00;\n      frame.data[4] = 0x32;\n      frame.data[5] = 0x01;\n      frame.data[6] = 0xF4;\n      frame.data[7] = 0xAA;\n      write(can, &frame, CAN_MTU);\n}\n\n/*\n  ECU Memory, based on VCDS response for now\n*/\nvoid handle_read_data_by_id(int can, struct canfd_frame frame) {\n  if(verbose) plog(\"Recieved Read Data by ID %02X %02X\\n\", frame.data[2], frame.data[3]);\n  char resp[120];\n  if(frame.data[2] == 0xF1) {\n    switch(frame.data[3]) {\n     case 0x87:\n       if(verbose) plog(\"Read data by ID 0x87\\n\");\n       resp[0] = frame.data[1] + 0x40;\n       resp[1] = frame.data[2];\n       resp[2] = 0x87;\n       resp[3] = 0x30;\n       resp[4] = 0x34;\n       resp[5] = 0x45;\n       resp[6] = 0x39;\n       resp[7] = 0x30;\n       resp[8] = 0x36;\n       resp[9] = 0x33;\n       resp[10] = 0x32;\n       resp[11] = 0x33;\n       resp[12] = 0x46;\n       resp[13] = 0x20; // Note VCDS pads with 55's\n       isotp_send_to(can, resp, 14, 0x77A);\n       break;\n      case 0x89:\n          if(verbose) plog(\"Read data by ID 0x89\\n\");\n          frame.can_id = 0x7E8;\n          frame.len = 8;\n          frame.data[0] = 0x07;\n          frame.data[1] = 0x62;\n          frame.data[2] = 0xF1;\n          frame.data[3] = 0x89;\n          frame.data[4] = 0x38; //8\n          frame.data[5] = 0x34; //4\n          frame.data[6] = 0x31; //1\n          frame.data[7] = 0x30; //0\n          write(can, &frame, CAN_MTU);\n        break;\n      case 0x9E:\n        if(verbose) plog(\"Read data by ID 0x9E\\n\");\n        resp[0] = frame.data[1] + 0x40;\n        resp[1] = frame.data[2];\n        resp[2] = 0x45; \n        resp[3] = 0x56;\n        resp[4] = 0x5F;\n        resp[5] = 0x47;\n        resp[6] = 0x61;\n        resp[7] = 0x74;\n        resp[8] = 0x65;\n        resp[9] = 0x77;\n        resp[10] = 0x45;\n        resp[11] = 0x56;\n        resp[12] = 0x43;\n        resp[13] = 0x6F;\n        resp[14] = 0x6E;\n        resp[15] = 0x74;\n        resp[16] = 0x69;\n        resp[17] = 0x00;\n        isotp_send(can, resp, 0x13);\n        break;\n      case 0xA2: \n        if(verbose) plog(\"Read data by ID 0xA2\\n\");\n        resp[0] = frame.data[1] + 0x40;\n        resp[1] = frame.data[2];\n        resp[2] = 0xA2;\n        resp[3] = 0x30; // 004010\n        resp[4] = 0x30;\n        resp[5] = 0x34;\n        resp[6] = 0x30;\n        resp[7] = 0x31;\n        resp[8] = 0x30;\n        isotp_send(can, resp, 9);\n        break;\n     default:\n        if(verbose) plog(\"Not responding to ID %02X\\n\", frame.data[3]);\n        break;\n     }\n  } else if(frame.data[2] == 0x06) {\n    switch(frame.data[3]) {\n     case 0x00:\n        if(verbose) plog(\"Read data by ID 0x9E\\n\");\n        resp[0] = frame.data[1] + 0x40;\n        resp[1] = frame.data[2];\n        resp[2] = 0x02; \n        resp[3] = 0x01;\n        resp[4] = 0x00;\n        resp[5] = 0x17;\n        resp[6] = 0x26;\n        resp[7] = 0xF2;\n        resp[8] = 0x00;\n        resp[9] = 0x00;\n        resp[10] = 0x5B;\n        resp[11] = 0x00;\n        resp[12] = 0x12;\n        resp[13] = 0x08;\n        resp[14] = 0x58;\n        resp[15] = 0x00;\n        resp[16] = 0x00;\n        resp[17] = 0x00;\n        resp[18] = 0x00;\n        resp[19] = 0x01;\n        resp[20] = 0x01;\n        resp[21] = 0x01;\n        resp[22] = 0x00;\n        resp[23] = 0x01;\n        resp[24] = 0x00;\n        resp[25] = 0x00;\n        resp[26] = 0x00;\n        resp[27] = 0x00;\n        resp[28] = 0x00;\n        resp[29] = 0x00;\n        resp[30] = 0x00;\n        resp[31] = 0x00;\n        isotp_send(can, resp, 0x21);\n       break;\n     case 0x01:\n          if(verbose) plog(\"Read data by ID 0x01\\n\");\n          send_error_roor(can, frame, 0x7E8);\n       break;\n     default:\n       if(verbose) plog(\"Not responding to ID %02X\\n\", frame.data[3]);\n       break;\n     }\n  } else {\n    if(verbose) plog(\"Unknown read data by ID %02X\\n\", frame.data[2]);\n  }\n}\n\n/*\n GM\n*/\n\n// Read DID from ID (GM)\n// For now we are only setting this up to work with the BCM\n// 244   [3]  02 1A 90\nvoid handle_gm_read_did_by_id(int can, struct canfd_frame frame) {\n  if(verbose) plog(\"Received GM Read DID by ID Request\\n\");\n  char resp[300];\n  char *buf;\n  char *tracenum = \"874602RA51950204\";\n  unsigned char chksum;\n  int pktsize;\n  switch(frame.data[2]) {\n    case 0x90:  // VIN\n      if(verbose) plog(\" + Requested VIN\\n\");\n      switch(fuzz_level) {\n        case 0:\n          if(verbose) plog(\"Sending VIN %s\\n\", vin);\n          resp[0] = frame.data[1] + 0x40;\n          resp[1] = frame.data[2];\n          memcpy(&resp[2], vin, strlen(vin));\n          isotp_send_to(can, resp, 3 + strlen(vin), 0x644);\n          break;\n        case 1:\n          if(verbose) plog(\"Fuzzing VIN with printable chars\\n\");\n          resp[0] = frame.data[1] + 0x40;\n          resp[1] = frame.data[2];\n          buf = gen_data(DATA_ALPHANUM, 17);\n          chksum = calc_vin_checksum(buf, 17);\n          buf[8] = chksum;\n          if(verbose) plog(\"Using VIN: %s\\n\", buf);\n          memcpy(&resp[2], buf, 17);\n          free(buf);\n          isotp_send_to(can, resp, 3 + 17, 0x644);\n          break;\n        case 2:\n        case 3:  // At 3 the ISOTP spec gets flaky\n          pktsize = rand() % 252;\n          if(verbose) plog(\"Fuzzing big VIN with printable chars\\n\");\n          resp[0] = frame.data[1] + 0x40;\n          resp[1] = frame.data[2];\n          buf = gen_data(DATA_ALPHANUM, pktsize);\n          chksum = calc_vin_checksum(buf, pktsize);\n          buf[8] = chksum;\n          if(verbose) plog(\"Using big VIN (%d chars): %s\\n\",pktsize, buf);\n          memcpy(&resp[2], buf, pktsize);\n          free(buf);\n          isotp_send_to(can, resp, 3 + pktsize, 0x644);\n          break;\n        case 4:\n          if(verbose) plog(\"Fuzzing VIN with binary data\\n\");\n          resp[0] = frame.data[1] + 0x40;\n          resp[1] = frame.data[2];\n          buf = gen_data(DATA_BINARY, 17);\n          chksum = calc_vin_checksum(buf, 17);\n          buf[8] = chksum;\n          if(verbose) print_bin(buf, 17);\n          memcpy(&resp[2], buf, 17);\n          free(buf);\n          isotp_send_to(can, resp, 3 + 17, 0x644);\n          break;\n        case 5:\n        default:\n          pktsize = rand() % 252;\n          if(verbose) plog(\"Fuzzing VIN with binary data with size %d\\n\", pktsize);\n          resp[0] = frame.data[1] + 0x40;\n          resp[1] = frame.data[2];\n          buf = gen_data(DATA_BINARY, pktsize);\n          if(verbose) print_bin(buf, pktsize);\n          memcpy(&resp[2], buf, pktsize);\n          free(buf);\n          isotp_send_to(can, resp, 3 + pktsize, 0x644);\n          break;\n       }\n      break;\n    case 0xA1:  // SDM Primary Key\n      if(verbose) plog(\" + Requested SDM Primary Key\\n\");\n      switch(fuzz_level) {\n        case 0:\n        default:\n          if(verbose) plog(\"Sending SDM Key %04X\\n\", 0x6966);\n          resp[0] = frame.data[1] + 0x40;\n          resp[1] = frame.data[2];\n          resp[2] = 0x69;\n          resp[3] = 0x66;\n          isotp_send_to(can, resp, 5, 0x644);\n          break;\n      }\n      break;\n    case 0xB4:  // Traceability Number\n      if(verbose) plog(\" + Requested Traceability Number\\n\");\n      switch(fuzz_level) {\n        case 0:\n        default:\n          if(verbose) plog(\"Sending Traceabiliity number %s\\n\", tracenum);\n          resp[0] = frame.data[1] + 0x40;\n          resp[1] = frame.data[2];\n          memcpy(&resp[2], tracenum, strlen(tracenum));\n          isotp_send_to(can, resp, 3 + strlen(tracenum), 0x644);\n          break;\n      }\n      break;\n    case 0xB7:  // Software Number\n      if(verbose) plog(\" + Requested Software Number\\n\");\n      switch(fuzz_level) {\n        case 0:\n        default:\n          if(verbose) plog(\"Sending SW # %d\\n\", 600);\n          resp[0] = frame.data[1] + 0x40;\n          resp[1] = frame.data[2];\n          resp[2] = 0x42;\n          resp[3] = 0xAA;\n          resp[4] = 6;\n          resp[5] = 2; // 600\n          resp[6] = 0x58;\n          isotp_send_to(can, resp, 6, 0x644);\n          break;\n      }\n      break;\n    case 0xCB:  // End Model Part #\n      if(verbose) plog(\" + Requested End Model Part Number\\n\");\n      switch(fuzz_level) {\n        case 0:\n        default:\n          if(verbose) plog(\"Sending End Model Part Number %d\\n\", 15804602);\n          resp[0] = frame.data[1] + 0x40;\n          resp[1] = frame.data[2];\n          resp[2] = 0x00;\n          resp[3] = 0xF1;\n          resp[4] = 0x28;\n          resp[5] = 0xBA;\n          isotp_send_to(can, resp, 6, 0x644);\n          break;\n      }\n      break;\n    default:\n      break;\n  }\n}\n\n/* GM Read Data via PID */\n/* 244   [5]  04 AA 03 02 07 */\n/* 544#0738408D8B000200 */\n/* 544#02508D8D00000000 */\nvoid handle_gm_read_data_by_id(int can, struct canfd_frame frame) {\n  if(verbose) plog(\"Received GM Read Data by ID Request\\n\");\n  int offset = 0;\n  int i;\n  int datacnt;\n  char datacpy[8];\n  if (frame.data[0] == 0xFE) offset = 1;\n  memcpy(&datacpy, &frame.data, 8);\n  if(frame.can_id == 0x7e0) {\n    frame.can_id = 0x5e8;\n  } else {\n    frame.can_id = 0x500 + (frame.can_id & 0xFF);\n  }\n  frame.len = 8;\n  switch(frame.data[2 + offset]) { // Subfunctions\n    case 0x00:  // Stop\n      if(verbose) plog(\" + Stop Data Request\\n\");\n      memset(frame.data, 0, 8);\n      write(can, &frame, CAN_MTU);\n      CLEAR_BIT(pending_data, PENDING_READ_DATA_BY_ID_GM);\n      break;\n    case 0x01:  // One Response\n      if(verbose) plog(\" + One Response\\n\");\n      for(i=3; i < datacpy[0]+1; i++) {\n        frame.data[0] = datacpy[i];\n        for(datacnt=1; datacnt < 8; datacnt++) {\n          frame.data[datacnt] = rand() % 256;\n        }\n        write(can, &frame, CAN_MTU);\n        sleep(0.5);\n      }\n      break;\n    case 0x02:  // Slow Rate\n      if(verbose) plog(\" + Slow Rate\\n\");\n      SET_BIT(pending_data, PENDING_READ_DATA_BY_ID_GM);\n      memcpy(&gm_data_by_id, &frame, sizeof(frame));\n      break;\n    case 0x03:  // Medium Rate\n      if(verbose) plog(\" + Medium Rate\\n\");\n      SET_BIT(pending_data, PENDING_READ_DATA_BY_ID_GM);\n      memcpy(&gm_data_by_id, &frame, sizeof(frame));\n      break;\n    case 0x04:  // Fast Rate\n      if(verbose) plog(\" + Fast Rate\\n\");\n      SET_BIT(pending_data, PENDING_READ_DATA_BY_ID_GM);\n      memcpy(&gm_data_by_id, &frame, sizeof(frame));\n      break;\n    default:\n      plog(\"Unknown subfunction timer\\n\");\n      break;\n  }\n}\n\n/* GM Diag format is either\n     101#FE 03 A9 81 52  (Functional addressing: Where FE is the extended address)\n     7E0#03 A9 81 52 (no extended addressing)\n*/\nvoid handle_gm_read_diag(int can, struct canfd_frame frame) {\n  if(verbose) plog(\"Received GM Read Diagnostic Request\\n\");\n  int offset = 0;\n  int i, total;\n  char resp[150];\n  if(frame.data[0] == 0xFE) offset = 1;\n  switch(frame.data[2 + offset]) { // Subfunctions\n    case UDS_READ_STATUS_BY_MASK:  // Read DTCs by mask\n      if(verbose) {\n        plog(\" + Read DTCs by mask\\n\");\n        if(frame.data[3 + offset] & DTC_SUPPORTED_BY_CALIBRATION) plog(\"   - Supported By Calibration\\n\");\n        if(frame.data[3 + offset] & DTC_CURRENT_DTC) plog(\"   - Current DTC\\n\");\n        if(frame.data[3 + offset] & DTC_TEST_NOT_PASSED_SINCE_CLEARED) plog(\"   - Tests not passed since DTC cleared\\n\");\n        if(frame.data[3 + offset] & DTC_TEST_FAILED_SINCE_CLEARED) plog(\"   - Tests failed since DTC cleared\\n\");\n        if(frame.data[3 + offset] & DTC_HISTORY) plog(\"   - DTC History\\n\");\n        if(frame.data[3 + offset] & DTC_TEST_NOT_PASSED_SINCE_POWER) plog(\"   - Tests not passed since power up\\n\");\n        if(frame.data[3 + offset] & DTC_CURRENT_DTC_SINCE_POWER) plog(\"   - Tests failed since power up\\n\");\n        if(frame.data[3 + offset] & DTC_WARNING_INDICATOR_STATE) plog(\"   - Warning Indicator State\\n\");\n      }\n      if(frame.can_id == 0x7e0) {\n        frame.can_id = 0x5e8;\n      } else {\n        frame.can_id = 0x500 + (frame.can_id & 0xFF);\n      }\n      frame.len = 8;\n      frame.data[0] = frame.data[2 + offset];\n      frame.data[1] = 0;    // DTC 1st byte\n      frame.data[2] = 0x30; // DTC 2nd byte\n      frame.data[3] = 0;\n      frame.data[4] = 0x6F; // Last Test/ This Ignition/ Last Clear bitflag\n      frame.data[5] = 0;\n      frame.data[6] = 0;\n      frame.data[7] = 0;\n      write(can, &frame, CAN_MTU);\n      sleep(0.2); // Instead of actually processing the FC\n      if(fuzz_level == 1) {\n        total = rand() % 1024;\n        if(verbose) plog(\"Sending %d DTCs\\n\", total);\n        for(i = 0; i < total; i++) {\n          frame.data[1] = rand() % 256;\n          frame.data[2] = (rand() % 255) + 1;\n          frame.data[3] = 0;\n          frame.data[4] = 0x6F; // Last DTC\n          write(can, &frame, CAN_MTU);\n          sleep(1);\n        }\n      }\n      frame.data[1] = 0; // Last frame must be a 0 DTC\n      frame.data[2] = 0;\n      frame.data[3] = 0;\n      frame.data[4] = 0xFF; // Last DTC\n      write(can, &frame, CAN_MTU);\n      break;\n    default:\n      if(verbose) plog(\" + Unknown subfunction request %02X\\n\", frame.data[2 + offset]);\n      break;\n  }\n}\n\n/*\n  Gateway\n*/\nvoid handle_vcds_710(int can, struct canfd_frame frame) {\n  if(verbose) plog(\"Received VCDS 0x710 gateway request\\n\");\n  char resp[150];\n  if(frame.data[0] == 0x30) { // Flow control\n    flow_control_push_to(can,0x77A);\n    return;\n  }\n  switch(frame.data[1]) {\n    //Pkt: 710#02 10 03 55 55 55 55 55 \n    case 0x10: // Diagnostic Session Control\n      frame.can_id = 0x77A;\n      frame.len = 8;\n      frame.data[0] = 0x06;\n      frame.data[1] = 0x50;\n      frame.data[2] = 0x03;\n      frame.data[3] = 0x00;\n      frame.data[4] = 0x32;\n      frame.data[5] = 0x01;\n      frame.data[6] = 0xF4;\n      frame.data[7] = 0xAA;\n      write(can, &frame, CAN_MTU);\n      break;\n    case 0x22: // Read Data By Identifier\n      if(frame.data[2] == 0xF1) {\n        switch(frame.data[3]) {\n        case 0x87: // VAG Number\n          if(verbose) plog(\"Read data by ID 0x87\\n\");\n          resp[0] = frame.data[1] + 0x40;\n          resp[1] = frame.data[2];\n          resp[2] = 0x87;\n          resp[3] = 0x35;\n          resp[4] = 0x51;\n          resp[5] = 0x45;\n          resp[6] = 0x39;\n          resp[7] = 0x30;\n          resp[8] = 0x37;\n          resp[9] = 0x35;\n          resp[10] = 0x33;\n          resp[11] = 0x30;\n          resp[12] = 0x43;\n          resp[13] = 0x20; // Note normally this would pad with AA's\n          isotp_send_to(can, resp, 14, 0x77A);\n        break;\n        case 0x89: // VAG Number\n          if(verbose) plog(\"Read data by ID 0x89\\n\");\n          frame.can_id = 0x77A;\n          frame.len = 8;\n          frame.data[0] = 0x07;\n          frame.data[1] = 0x62;\n          frame.data[2] = 0xF1;\n          frame.data[3] = 0x89;\n          frame.data[4] = 0x33; //3\n          frame.data[5] = 0x32; //2\n          frame.data[6] = 0x30; //0\n          frame.data[7] = 0x33; //3\n          write(can, &frame, CAN_MTU);\n        break;\n        case 0x91: // VAG Number\n          if(verbose) plog(\"Read data by ID 0x91\\n\");\n          resp[0] = frame.data[1] + 0x40;\n          resp[1] = frame.data[2];\n          resp[2] = 0x87;\n          resp[3] = 0x35;\n          resp[4] = 0x51;\n          resp[5] = 0x45;\n          resp[6] = 0x39;\n          resp[7] = 0x30;\n          resp[8] = 0x37;\n          resp[9] = 0x35;\n          resp[10] = 0x33;\n          resp[11] = 0x30;\n          resp[12] = 0x41;\n          resp[13] = 0x20; // Note normally this would pad with AA's\n          isotp_send_to(can, resp, 14, 0x77A);\n        break;\n        default:\n          if(verbose) plog(\"NOTE: Read data by unknown ID %02X\\n\", frame.data[3]);\n          resp[0] = frame.data[1] + 0x40;\n          resp[1] = frame.data[2];\n          resp[2] = 0x87;\n          resp[3] = 0x35;\n          resp[4] = 0x51;\n          resp[5] = 0x45;\n          resp[6] = 0x39;\n          resp[7] = 0x30;\n          resp[8] = 0x37;\n          resp[9] = 0x35;\n          resp[10] = 0x33;\n          resp[11] = 0x30;\n          resp[12] = 0x41;\n          resp[13] = 0x20; // Note normally this would pad with AA's\n          isotp_send_to(can, resp, 14, 0x77A);\n        break;\n       \n      }\n    } else {\n      if (verbose) plog(\"Unknown read data by Identifier %02X\\n\", frame.data[2]);\n    }\n    break;\n  }\n}\n\n// return Mode/SIDs in english\nchar *get_mode_str(struct canfd_frame frame) {\n  switch(frame.data[1]) {\n    case OBD_MODE_SHOW_CURRENT_DATA:\n       return \"Show current Data\";\n       break;\n    case OBD_MODE_SHOW_FREEZE_FRAME:\n       return \"Show freeze frame\";\n       break;\n    case OBD_MODE_READ_DTC:\n       return \"Read DTCs\";\n       break;\n    case OBD_MODE_CLEAR_DTC:\n       return \"Clear DTCs\";\n       break;\n    case OBD_MODE_TEST_RESULTS_NON_CAN:\n       return \"Mode Test Results (Non-CAN)\";\n       break;\n    case OBD_MODE_TEST_RESULTS_CAN:\n       return \"Mode Test Results (CAN)\";\n       break;\n    case OBD_MODE_READ_PENDING_DTC:\n       return \"Read Pending DTCs\";\n       break;\n    case OBD_MODE_CONTROL_OPERATIONS:\n       return \"Control Operations\";\n       break;\n    case OBD_MODE_VEHICLE_INFORMATION:\n       return \"Vehicle Information\";\n       break;\n    case OBD_MODE_READ_PERM_DTC:\n       return \"Read Permanent DTCs\";\n       break;\n    case UDS_SID_DIAGNOSTIC_CONTROL:\n       return \"Diagnostic Control\";\n       break;\n    case UDS_SID_ECU_RESET:\n       return \"ECU Reset\";\n       break;\n    case UDS_SID_CLEAR_DTC:\n       return \"UDS Clear DTCs\";\n       break;\n    case UDS_SID_READ_DTC:\n       return \"UDS Read DTCs\";\n       break;\n    case UDS_SID_GM_READ_DID_BY_ID:\n       return \"Read DID by ID (GM)\";\n       break;\n    case UDS_SID_RESTART_COMMUNICATIONS:\n       return \"Restore Normal Commnications\";\n       break;\n    case UDS_SID_READ_DATA_BY_ID:\n       return \"Read DATA By ID\";\n       break;\n    case UDS_SID_READ_MEM_BY_ADDRESS:\n       return \"Read Memory By Address\";\n       break;\n    case UDS_SID_READ_SCALING_BY_ID:\n       return \"Read Scalling Data by ID\";\n       break;\n    case UDS_SID_SECURITY_ACCESS:\n       return \"Security Access\";\n       break;\n    case UDS_SID_COMMUNICATION_CONTROL:\n       return \"Communication Control\";\n       break;\n    case UDS_SID_READ_DATA_BY_ID_PERIODIC:\n       return \"Read DATA By ID Periodically\";\n       break;\n    case UDS_SID_DEFINE_DATA_ID:\n       return \"Define DATA By ID\";\n       break;\n    case UDS_SID_WRITE_DATA_BY_ID:\n       return \"Write DATA By ID\";\n       break;\n    case UDS_SID_IO_CONTROL_BY_ID:\n       return \"Input/Output Control By ID\";\n       break;\n    case UDS_SID_ROUTINE_CONTROL:\n       return \"Routine Control\";\n       break;\n    case UDS_SID_REQUEST_DOWNLOAD:\n       return \"Request Download\";\n       break;\n    case UDS_SID_REQUEST_UPLOAD:\n       return \"Request Upload\";\n       break;\n    case UDS_SID_TRANSFER_DATA:\n       return \"Transfer DATA\";\n       break;\n    case UDS_SID_REQUEST_XFER_EXIT:\n       return \"Request Transfer Exit\";\n       break;\n    case UDS_SID_REQUEST_XFER_FILE:\n       return \"Request Transfer File\";\n       break;\n    case UDS_SID_WRITE_MEM_BY_ADDRESS:\n       return \"Write Memory By Address\";\n       break;\n    case UDS_SID_TESTER_PRESENT:\n       return \"Tester Present\";\n       break;\n    case UDS_SID_ACCESS_TIMING:\n       return \"Access Timing\";\n       break;\n    case UDS_SID_SECURED_DATA_TRANS:\n       return \"Secured DATA Transfer\";\n       break;\n    case UDS_SID_CONTROL_DTC_SETTINGS:\n       return \"Control DTC Settings\";\n       break;\n    case UDS_SID_RESPONSE_ON_EVENT:\n       return \"Response On Event\";\n       break;\n    case UDS_SID_LINK_CONTROL:\n       return \"Link Control\";\n       break;\n    case UDS_SID_GM_PROGRAMMED_STATE:\n       return \"Programmed State (GM)\";\n       break;\n    case UDS_SID_GM_PROGRAMMING_MODE:\n       return \"Programming Mode (GM)\";\n       break;\n    case UDS_SID_GM_READ_DIAG_INFO:\n       return \"Read Diagnostic Information (GM)\";\n       break;\n    case UDS_SID_GM_READ_DATA_BY_ID:\n       return \"Read DATA By ID (GM)\";\n       break;\n    case UDS_SID_GM_DEVICE_CONTROL:\n       return \"Device Control (GM)\";\n       break;\n    default:\n       printf(\"Unknown mode/sid (%02X)\\n\", frame.data[1]);\n       return \"\";\n  }\n}\n\n// Prints raw packet in ID#DATA format\nvoid print_pkt(struct canfd_frame frame) {\n  int i;\n  plog(\"Pkt: %02X#\", frame.can_id);\n  for(i = 0; i < frame.len; i++) {\n    plog(\"%02X \", frame.data[i]);\n  }\n  plog(\"\\n\");\n}\n\n// Prints binary data in hex format\nvoid print_bin(unsigned char *bin, int size) {\n  int i;\n  for(i = 0; i < size; i++) {\n    plog(\"%02X \", bin[i]);\n  }\n  plog(\"\\n\");\n}\n\n// Handles the incomming CAN Packets\n// Each ID that deals with specific controllers a note is\n// given where that info came from.  There could be a lot of overlap\n// and exceptions here. -- Craig\nvoid handle_pkt(int can, struct canfd_frame frame) {\n  if(DEBUG) print_pkt(frame);\n  switch(frame.can_id) {\n    case 0x243: // EBCM / GM / Chevy Malibu 2006\n      switch(frame.data[1]) {\n        case UDS_SID_TESTER_PRESENT:\n          if(verbose > 1) plog(\"Received TesterPresent\\n\");\n          generic_OK_resp_to(can, frame, 0x643);\n          break;\n        case UDS_SID_GM_READ_DIAG_INFO:\n          handle_gm_read_diag(can, frame);\n          break;\n        \n        default:\n          if(verbose) print_pkt(frame);\n          if(verbose) plog(\"Unhandled mode/sid: %s\\n\", get_mode_str(frame));\n          break;\n      }\n      break;\n    case 0x244: // Body Control Module / GM / Chevy Malibu 2006\n      if(frame.data[0] == 0x30) { // Flow control\n        flow_control_push_to(can, 0x644);\n        return;\n      }\n      switch(frame.data[1]) {\n        case UDS_SID_TESTER_PRESENT:\n          if(verbose > 1) plog(\"Received TesterPresent\\n\");\n          generic_OK_resp_to(can, frame, 0x644);\n          break;\n        case UDS_SID_GM_READ_DIAG_INFO:\n          handle_gm_read_diag(can, frame);\n          break;\n        case UDS_SID_GM_READ_DATA_BY_ID:\n          handle_gm_read_data_by_id(can, frame);\n          break;\n        case UDS_SID_GM_READ_DID_BY_ID:\n          handle_gm_read_did_by_id(can, frame);\n          break;\n        default:\n          if(verbose) print_pkt(frame);\n          if(verbose) plog(\"Unhandled mode/sid: %s\\n\", get_mode_str(frame));\n          break;\n      }\n      break;\n    case 0x24A: // Power Steering / GM / Chevy Malibu 2006\n      switch(frame.data[1]) {\n        default:\n          if(verbose) print_pkt(frame);\n          if(verbose) plog(\"Unhandled mode/sid: %s\\n\", get_mode_str(frame));\n          break;\n      }\n      break;\n    case 0x350: // Unsure.  Seen RTRs to this when requesting VIN\n      if (frame.can_id & CAN_RTR_FLAG) {\n        if (verbose) plog(\"Received a RTR at ID %02X\\n\", frame.can_id);\n      }\n      break;\n    case 0x710: // VCDS\n      if(verbose) print_pkt(frame);\n      handle_vcds_710(can, frame);\n      break;\n    case 0x7df:\n    case 0x7e0:  // Sometimes flow control comes here\n      if(verbose) print_pkt(frame);\n      if(frame.data[0] == 0x30 && gBufLengthRemaining > 0) flow_control_push(can);\n      if(frame.data[0] == 0 || frame.len == 0) return;\n      if(frame.data[0] > frame.len) return;\n      switch (frame.data[1]) {\n        case OBD_MODE_SHOW_CURRENT_DATA:\n          handle_current_data(can, frame);\n          break;\n        case OBD_MODE_SHOW_FREEZE_FRAME: \n          handle_freeze_frame(can, frame);\n          break;\n        case OBD_MODE_READ_DTC:\n          handle_stored_codes(can, frame);\n          break;\n        case OBD_MODE_READ_PENDING_DTC:\n          handle_pending_codes(can, frame);\n          break;\n        case OBD_MODE_VEHICLE_INFORMATION:\n          handle_vehicle_info(can, frame);\n          break;\n        case OBD_MODE_READ_PERM_DTC:\n          handle_perm_codes(can, frame);\n          break;\n        case UDS_SID_DIAGNOSTIC_CONTROL: // DSC\n          handle_dsc(can, frame);\n          break;\n        case UDS_SID_READ_DATA_BY_ID:\n          handle_read_data_by_id(can, frame);\n          break;\n        case UDS_SID_TESTER_PRESENT:\n          if(verbose > 1) plog(\"Received TesterPresent\\n\");\n          generic_OK_resp(can, frame);\n          break;\n        case UDS_SID_GM_READ_DIAG_INFO:\n          handle_gm_read_diag(can, frame);\n          break;\n        default:\n          //if(verbose) plog(\"Unhandled mode/sid: %02X\\n\", frame.data[1]);\n          if(verbose) plog(\"Unhandled mode/sid: %s\\n\", get_mode_str(frame));\n          break;\n      }\n      break;\n    default:\n      if (DEBUG) print_pkt(frame);\n      if (DEBUG) plog(\"DEBUG: missed ID %02X\\n\", frame.can_id);\n      break;\n  }\n}\n\nint main(int argc, char *argv[]) {\n  int opt, ret;\n  int can;\n  int nbytes;\n  struct ifreq ifr;\n  struct sockaddr_can addr;\n  struct iovec iov;\n  struct msghdr msg;\n  struct canfd_frame frame;\n  char ctrlmsg[CMSG_SPACE(sizeof(struct timeval)) + CMSG_SPACE(sizeof(__u32))];\n  struct sigaction act;\n  struct timeval timeo;\n  fd_set rdfs;\n\n  verbose = 0;\n  act.sa_handler = intHandler;\n  sigaction(SIGINT, &act, NULL);\n  sigaction(SIGHUP, &act, NULL);\n  srand(time(NULL));\n\n  while ((opt = getopt(argc, argv, \"cV:zl:vFh?\")) != -1) {\n    switch(opt) {\n        case 'c':\n          keep_spec = 1;\n          break;\n        case 'v':\n          verbose++;\n          break;\n        case 'V':\n          vin = optarg;\n          break;\n        case 'F':\n          no_flow_control = 1;\n          break;\n        case 'l':\n          plogfp = fopen(optarg, \"a+\");\n          break;\n        case 'z':\n          fuzz_level++;\n          break;\n        case 'h':\n        case '?':\n        default:\n          usage(argv[0], NULL);\n          break;\n    }\n  }\n\n  if (optind >= argc) usage(argv[0], \"You must specify at least one can device\");\n\n  // Create a new raw CAN socket\n  can = socket(PF_CAN, SOCK_RAW, CAN_RAW);\n  if(can < 0) usage(argv[0], \"Couldn't create raw socket\");\n\n  addr.can_family = AF_CAN;\n  memset(&ifr.ifr_name, 0, sizeof(ifr.ifr_name));\n  strncpy(ifr.ifr_name, argv[optind], strlen(argv[optind]));\n  if (verbose) plog(\"Using CAN interface %s\\n\", ifr.ifr_name);\n  if (ioctl(can, SIOCGIFINDEX, &ifr) < 0) {\n    perror(\"SIOCGIFINDEX\");\n    exit(1);\n  }\n  addr.can_ifindex = ifr.ifr_ifindex;\n\n  if (bind(can, (struct sockaddr *)&addr, sizeof(addr)) < 0) {\n        perror(\"bind\");\n        return 1;\n  }\n\n  iov.iov_base = &frame;\n  iov.iov_len = sizeof(frame);\n  msg.msg_name = &addr;\n  msg.msg_namelen = sizeof(addr);\n  msg.msg_iov = &iov;\n  msg.msg_iovlen = 1;\n  msg.msg_control = &ctrlmsg;\n  msg.msg_controllen = sizeof(ctrlmsg);\n  msg.msg_flags = 0;\n\n  if(verbose) plog(\"Fuzz level set to: %d\\n\", fuzz_level);\n  gettimeofday(&start_tv, NULL);\n  running = 1;\n  while(running) {\n    FD_ZERO(&rdfs);\n    FD_SET(can, &rdfs);\n  \n    timeo.tv_sec  = 0;\n    timeo.tv_usec = 10000 * 20; // 20 ms  \n\n    if ((ret = select(can+1, &rdfs, NULL, NULL, &timeo)) < 0) {\n      running = 0;\n      continue;\n    }\n\n    if (FD_ISSET(can, &rdfs)) {\n      nbytes = recvmsg(can, &msg, 0);\n      if (nbytes < 0) {\n        perror(\"read\");\n        return 1;\n      }\n      if ((size_t)nbytes != CAN_MTU) {\n        fprintf(stderr, \"read: incomplete CAN frame\\n\");\n        return 1;\n      }\n      handle_pkt(can, frame);\n    }\n\n    handle_pending_data(can);\n  }\n\n  plog(\"Got Interrupt.  Shutting down gracefully\\n\");\n  if(plogfp) fclose(plogfp);\n\n}\n"
  },
  {
    "path": "uds-server.h",
    "content": "/* (c) 2015 Open Garages */\n\n/* Helper Macros */\n#define SET_BIT(val, bitIndex) val |= (1 << bitIndex)\n#define CLEAR_BIT(val, bitIndex) val &= ~(1 << bitIndex)\n#define TOGGLE_BIT(val, bitIndex) val ^= (1 << bitIndex)\n#define IS_SET(val, bitIndex) (val & (1 << bitIndex))\n\n/* OBD-II Modes */\n#define OBD_MODE_SHOW_CURRENT_DATA        0x01\n#define OBD_MODE_SHOW_FREEZE_FRAME        0x02\n#define OBD_MODE_READ_DTC                 0x03\n#define OBD_MODE_CLEAR_DTC                0x04\n#define OBD_MODE_TEST_RESULTS_NON_CAN     0x05\n#define OBD_MODE_TEST_RESULTS_CAN         0x06\n#define OBD_MODE_READ_PENDING_DTC         0x07\n#define OBD_MODE_CONTROL_OPERATIONS       0x08\n#define OBD_MODE_VEHICLE_INFORMATION      0x09\n#define OBD_MODE_READ_PERM_DTC            0x0A\n\n/* UDS SIDs */\n#define UDS_SID_DIAGNOSTIC_CONTROL        0x10 // GMLAN = Initiate Diagnostics\n#define UDS_SID_ECU_RESET                 0x11\n#define UDS_SID_GM_READ_FAILURE_RECORD    0x12 // GMLAN\n#define UDS_SID_CLEAR_DTC                 0x14\n#define UDS_SID_READ_DTC                  0x19\n#define UDS_SID_GM_READ_DID_BY_ID         0x1A // GMLAN - Read DID By ID\n#define UDS_SID_RESTART_COMMUNICATIONS    0x20 // GMLAN - Restart a stopped com\n#define UDS_SID_READ_DATA_BY_ID           0x22\n#define UDS_SID_READ_MEM_BY_ADDRESS       0x23\n#define UDS_SID_READ_SCALING_BY_ID        0x24\n#define UDS_SID_SECURITY_ACCESS           0x27\n#define UDS_SID_COMMUNICATION_CONTROL     0x28 // GMLAN Stop Communications\n#define UDS_SID_READ_DATA_BY_ID_PERIODIC  0x2A\n#define UDS_SID_DEFINE_DATA_ID            0x2C\n#define UDS_SID_WRITE_DATA_BY_ID          0x2E\n#define UDS_SID_IO_CONTROL_BY_ID          0x2F\n#define UDS_SID_ROUTINE_CONTROL           0x31\n#define UDS_SID_REQUEST_DOWNLOAD          0x34\n#define UDS_SID_REQUEST_UPLOAD            0x35\n#define UDS_SID_TRANSFER_DATA             0x36\n#define UDS_SID_REQUEST_XFER_EXIT         0x37\n#define UDS_SID_REQUEST_XFER_FILE         0x38\n#define UDS_SID_WRITE_MEM_BY_ADDRESS      0x3D\n#define UDS_SID_TESTER_PRESENT            0x3E\n#define UDS_SID_ACCESS_TIMING             0x83\n#define UDS_SID_SECURED_DATA_TRANS        0x84\n#define UDS_SID_CONTROL_DTC_SETTINGS      0x85\n#define UDS_SID_RESPONSE_ON_EVENT         0x86\n#define UDS_SID_LINK_CONTROL              0x87\n#define UDS_SID_GM_PROGRAMMED_STATE       0xA2\n#define UDS_SID_GM_PROGRAMMING_MODE       0xA5\n#define UDS_SID_GM_READ_DIAG_INFO         0xA9\n#define UDS_SID_GM_READ_DATA_BY_ID        0xAA\n#define UDS_SID_GM_DEVICE_CONTROL         0xAE\n\n/* GM READ DIAG SUB FUNCS */\n#define UDS_READ_STATUS_BY_MASK           0x81\n/* DTC MASK Bitflags */\n#define DTC_SUPPORTED_BY_CALIBRATION      1\n#define DTC_CURRENT_DTC                   2\n#define DTC_TEST_NOT_PASSED_SINCE_CLEARED 4\n#define DTC_TEST_FAILED_SINCE_CLEARED     8\n#define DTC_HISTORY                       16\n#define DTC_TEST_NOT_PASSED_SINCE_POWER   32\n#define DTC_CURRENT_DTC_SINCE_POWER       64\n#define DTC_WARNING_INDICATOR_STATE       128\n\n/* Periodic Data Message types */\n#define PENDING_READ_DATA_BY_ID_GM         1\n\n"
  },
  {
    "path": "vintest.sh",
    "content": "./uds-server -v -V \"PWN3D OP3N G4R4G3\" can0\n"
  }
]