Практическое руководство по взлому (и защите) игр на Unity
Когда речь идёт о программном обеспечении, термин «взлом» зачастую ассоциируют с пиратством и нарушением авторских прав. Данная статья не об этом; напротив, я решительно не одобряю любые действия, которые прямо или косвенно могут навредить другим разработчикам. Тем не менее, эта статья всё же является практическим руководством по взлому. Используя инструменты и методы о которых далее пойдёт речь, вы сможете проверить защиту собственной Unity игры и узнаете, как обезопасить её от взлома и кражи ресурсов.
Введение
В основе взлома лежит знание: необходимо понимать особенности компиляции Unity-проекта, чтобы его взломать. Прочитав статью, вы узнаете, каким образом Unity компилирует ресурсы игры и как извлечь из них исходные материалы: текстуры, шейдеры, 3D-модели и скрипты. Эти навыки будут полезны не только для анализа безопасности проекта, но также для его продвинутой отладки. В связи с закрытостью исходного кода, Unity часто работает как «черный ящик» и порой единственный способ понять, что именно в нём происходит — это изучение скомпилированной версии скриптов. Кроме прочего, декомпиляция чужой игры может стать серьёзным подспорьем в поиске её секретов и «пасхальных яиц». Например, именно таким образом было найдено решение финальной головоломки в игре FEZ.
Находим ресурсы игры
Рассмотрим для примера игру, собранную под ОС Windows и загруженную через Steam. Чтобы добраться до директории, в которой находятся нужные нам ресурсы, откроем окно свойств игры в библиотеке Steam и в закладке «Local files» нажмём «Browse local files…».
Когда Unity компилирует проект под Windows, ресурсы всегда упаковываются по схожей схеме: исполняемый файл (например, Game.exe ) будет находится в корне директории игры, а по соседству расположится директория, содержащая все игровые ресурсы — Game_Data .
Извлекаем текстуры и шейдеры
Большинство ресурсов Unity-проекта упаковываются в файлы проприетарного формата с расширениями .assets и .resources . Наиболее популярный на сегодняшний день инструмент для просмотра таких файлов и извлечения из них ресурсов — Unity Assets Explorer.
Графический интерфейс программы не отличается удобством, а также она страдает от нескольких критических багов. Не взирая на это, программа вполне способна извлечь большинство текстур и шейдеров из игры. Полученные в результате текстуры будут иметь формат DDS, который можно «прочитать» с помощью Windows Texture Viewer.
С шейдерами ситуация обстоит сложнее: они извлекаются в уже скомпилированным виде и, насколько мне известно, решений для их автоматической трансляции в удобочитаемый формат не существует. Тем не менее, это обстоятельство не мешает импортировать и использовать полученные шейдеры в другом Unity-проекте. Не забывайте, однако, что подобная «кража» нарушает авторские права и является актом пиратства.
Извлекаем 3D-модели
Трёхмерные модели в типовой Unity-сборке «разбросаны» по различным ресурсам, а некоторые из них и вовсе могут генерироваться во время игры. Вместо копания в файлах, существует интересная альтернатива — получить данные о геометрии прямиком из памяти графического ускорителя. Когда игра запущена, вся информация о текстурах и моделях, видимых на экране, находится в памяти видеокарты. С помощью утилиты 3D Ripper DX можно извлечь всю эту информацию и сохранить в формате, понятном 3D-редакторам (например, 3D Studio Max). Учтите, что программа не самая простая в обращении — возможно, придётся обратиться к документации.
Взламываем PlayerPrefs
PlayerPrefs — это класс из стандартной библиотеки Unity, который позволяет сохранять данные в долговременную память устройства. Он часто используется разработчиками для хранения различных настроек, достижений, прогресса игрока и другой информации о состоянии игры. На ОС Windows эти данные сохраняются в системном реестре по следующему пути: HKEY_CURRENT_USER\Software\[company name]\[game name] .
Защищаем PlayerPrefs
Помешать пользователю редактировать значения в системном реестре мы не в силах. А вот проверить, изменялись ли эти значения без нашего ведома — вполне реально. В этом нам помогут хеш-функции: сравнив контрольные суммы хранимых данных, мы сможем убедиться, что никто и ничто, кроме нашего кода эти данные не изменяло.
Приведенный выше класс — упрощенный пример реализации, работающий со строковыми переменными. Для инициализации ему необходимо передать секретный ключ и список PlayerPrefs-ключей, значения которых должны быть защищены:
Затем его можно использовать следующим образом:
При каждом вызове метода Save , на основе значений всех параметров, ключи которых были переданы классу при инициализации, вычисляется и сохраняется контрольная сумма. Используя метод HasBeenEdited мы затем можем проверить, изменялись ли защищенные параметры без нашего ведома.
Взламываем исходный код
Для Windows-сборок Unity компилирует и сохраняет исходный код всех игровых скриптов в директорию Managed . Интересуют нас следующие библиотеки: Assembly-CSharp.dll , Assembly-CSharp-firstpass.dll и Assembly-UnityScript.dll .
Для декомпиляции и просмотра managed-кода .NET библиотек (коими и являются наши жертвы) существуют довольно удобные и при этом бесплатные утилиты: IlSpy и dotPeek.
Данных подход особенно эффективен для наших целей: Unity очень скупо оптимизирует исходный код игровых скриптов, практически не изменяя его структуру, а также не скрывает названия переменных. Это позволяет с легкостью читать и понимать декомпилированый материал.
Защищаем исходный код
Раз Unity не заботится о сохранности нашего кода — сделаем это сами. Благо, существует утилита, готовая автоматически зашифровать плоды нашего интеллектуального труда: Unity 3D Obfuscator.
И хотя программа отлично справляется со своими обязанностями, многие классы, адресуемые извне родной библиотеки, всё же не могут быть зашифрованы без риска нарушения связанности — будьте осторожны!
Взламываем память игры
Cheat Engine — широко известная программа для взлома игр. Она находит ту область оперативной памяти, которая принадлежит процессу запущенной игры и позволяет произвольно её изменять.
Эта программа пользуется тем фактом, что разработчики игр очень редко защищают значения переменных. Рассмотрим следующий пример: в некой игре у нас есть 100 патронов; используя Cheat Engine, можно выполнить поиск участков памяти, которые хранят значение «100». Затем мы делаем выстрел — запас патронов составляет 99 единиц. Снова сканируем память, но теперь ищем значение «99». После нескольких подобных итераций можно с легкостью обнаружить расположение большинства переменных игры и произвольно их изменять.
Защищаем память игры
Cheat Engine столь эффективна от того, что значения переменных хранятся в своём изначальном виде, без какой-либо защиты. Серьёзно усложнить жизнь «читерам» довольно просто: нужно лишь немного изменить способ работы с переменными. Создадим структуру SafeFloat , которая послужит нам безопасной заменой стандартного float :
Использовать нашу новую структуру можно следующим образом:
Если вы выводите значения переменных на экран, хакеры всё ещё смогут перехватить и поменять их, но это не повлияет на действительные значения, хранящиеся в памяти и использующиеся в логике игры.
Заключение
К сожалению, существует не так уж много способов защитить игру от взлома. Будучи установленной на пользовательское устройство, она фактически раскрывает все ваши текстуры, модели и исходный код. Если кто-то захочет декомпилировать игру и украсть ресурсы — это лишь вопрос времени.
Невзирая на это, существуют действенные методы, которые позволят серьёзно усложнить жизнь злоумышленникам. Это не значит, что нужно вдаваться в панику, шифровать весь исходный код и защищать каждую переменную, но по крайней мере задумайтесь, какие ресурсы вашего проекта действительно важны и что вы можете сделать для их защиты.
Can You Share Unity Projects?
Ever wanted to allow more than one person to work on a project without overwriting each others work? This can be extremely frustrating for new development teams who have not used any version control system before. The ones available to Unity have been difficult to use at times leading up to now. I want to talk about a few options that I have come across.
Yes, you can share Unity projects. Git, shared drives, scene fusion, and Unity collaborate are several options that may work well for your projects.
Option 1: Git
Please enable JavaScript
If you look around very long for any suggestions on this topic, Git is one of the most commonly suggested ways to share a Unity project. Quite frankly, I think it may be one of the worst.
In a classroom, I spent two different years trying to get Git to work properly. It was either over mine and the students heads or just simply isn’t a good option. I think it may be both. I acknowledge that code is extremely important for game designers, but it’s not the only aspect of game development.
Git was not very easy to use. I even tried to use some basic applications like GitHub Desktop and SourceTree. Both were great tools. We used GitHub a bit for web design. However, for game development it just didn’t feel sufficient. Here’s why:
GitHub is really meant for code management. So it worked very well for all of the scripting we had in our game. However, as soon as we mixed in some 3D models and textures, it just didn’t perform as we wanted to. Perhaps others found better solutions for transferring these types of files back and forth, but ultimately it felt like we were doubling the work to move files back and forth between two people. We would transfer code through git and then use a shared drive for other file types.
There are a lot of people that swear by this method, but I have not found it to be that great. It may be best suited for someone working on multiple computers and wishes to have a true version control system that they can revert back to older versions if necessary. It is certainly better than no alternative, but I believe there to be better ways to share a Unity project.
Option 2: Shared Drives
This is the system we have most frequently used in the classroom. It’s the easiest for students to understand. We have a network drive but it could be done with something like Google Drive. It’s an easy way to share a project and make it accessible from multiple projects. The downside is that you are still limited to one person using the project at a time.
However, on our networked shared drive we have a backup system that has saved us multiple times. If a project becomes corrupt, we can back up a few hours or a few days, depending on what we need. It has saved quite a few game development projects!
Option 3: Scene Fusion
Scene Fusion is something that we have used in the classroom quite a bit this year. Students get a bit frustrated with the setup, but if you read the instructions it’s pretty well a one time thing. If you have a consistent workflow on your team, it’s a really awesome tool. We used it to allow multiple people to work in a Unity Scene at one time.
Once you grasp how it works, it’s nice to use. Students found it to be a bit slow and cumbersome, but it was their lack of experience with Unity that made it feel that way. Someone with a bit of Unity experience would find it to be a great tool. I do highly recommend Scene Fusion as a method for working in a Unity scene at one time. In fact, I recommend so much we purchase a classroom license two years in a row, which was not the cheapest.
The developers are great with support as well. Anytime we did run into issues or if I had questions, they were quick to respond and eager to help out.
Here is a demo of Scene Fusion, as I know many have not heard of it.
Option 4: Unity Collaborate Using Plastic SCM (Recommended)
I recommend Unity Collaborate now that they moved to Plastic SCM. Plastic SCM was a solution we also looked at after finding Git wasn’t a great option for us. It did work a bit, but it was again another cumbersome system originally before it was fully integrated into Unity.
Now, Collaborate has completly moved to it. Anyone who used Unity Collaborate prior to this change likely found themselves a bit frustrated once they hit the 1GB limit. 1GB felt extremely low as students were adding quite a few image files and trying out Unity assets. When students aren’t real familiar with optimization, 1GB is used up really quick.
With PlasticSCM, developers can have up to three people working on a project for free and the project can be up to 5GB. This is a huge improvement.
What Makes Plastic SCM Better than Git For Unity?
Git is certainly more popular than Plastic SCM. If you are a developer of any kind of software, you have likely heard of Git, or the largest platform using Git, GitHub.
GitHub (or Git) is a great platform for code itself. However, as anyone who works in game development is aware, a game is not made up of only code, but includes image files, potentially video, and other media based files that require a significant amount of storage.
With GitHub, you cannot exceed a push of more than 100MB at a time and can’t push a file that exceeds more than 25MB. If you download a single environment pack it is likely more than 100MB. We would spend quite a bit of time trying to eliminate files that we weren’t using in the project to try and lower our file size. Sure, this probably should be done anyhow, but if you’re learning, there are more important things to focus on.
PlasticSCM can really support the media files. It’s built for that. You as the developer have the choice to choose how large of repository you are working with. When you aren’t severely limited on space, it makes the process much more enjoyable.
The Price of Plastic SCM for Unity
The downside of Plastic SCM is that you are going to pay for larger repositories. You get 5GB for free, which is a significant amount. However, you will be surprised how quickly 5GB goes if you’re working with a 3D environment. The good news is that space is only getting cheaper. Right now, an additional 20 GB will cost $5 per month. And each additional 25GB will cost another $5 per month. This is extremely affordable.
In addition, the Plastic SCM free version only supports up to three developers. If you wish to add additional developers it will cost $23 / month for each additional developer.
How to Move From Unity Collaborate to Plastic SCM
- Ensure you are using one of the versions of Unity that supports Plastic SCM integration. According to Plastic SCM the following versions and later are supported:
- 2019.4. 32f1 or later.
- 2020.3. 20f1 or later.
- 2021.1. 25f1 or later.
- 2021.2. 0b16 or later.
- 2022.1. 0a12 or later.
- Go to Project Settings -> Services -> Collaborate
- If you turn off Collaborate, you are now using Plastic SCM.
You will then need to download Plastic SCM and set that up. Instead of writing everything out, I felt the video below did a great job of walking you through it for each team member.
Travis Tracy has spent 12 years in the 3D Design industry. In the evenings, he frequently spent time learning about programming, which ultimately led him into game development. In 2012, he became an instructor and continues to teach 3D Design and Game Development in Oklahoma.
Recent Content
Building a game development team that works well can be quite difficult. I wanted to look back at my experience in a classroom, working with nearly fifty different teams and put together a list of.
If you are preparing to start a game development project, then you probably understand the importance of building a game design document. Having a game design document will help you ensure you have.
report this ad
About Us
Hello! My name is Travis Tracy, I spent twelve years in the 3D industry and have been teaching game development for the last nine years in Oklahoma. I hope to share many of my observations and passions related to this industry with you. When not in the classroom, I enjoy spending time in game jams and refining my own skills in this industry that is always changing.
LEGAL INFORMATION
Indie Game Haven is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com. We are compensated for referring traffic and business to Amazon and other companies linked to on this site.
report this ad
Unity5. Декомпиляция или взлом скриптов. + Видео
Уроки
Как взломать игровые скрипты.
Для того что бы, показать как взломать и посмотреть игровые скрипты, которые созданные в игровом движке Unity5, мы создадим пустой проект с каким-нибудь простым скриптом, например таймер.
Далее, сохраним сцену и скомпилируем все это в игру для платформы windows.
Укажем папку для сохранения игры и назовем файл к примеру test.
По сути, у нас уже готова игра с простым скриптом таймера, давайте попробуем взломать нашу игру и посмотреть из чего состоит этот скрипт.
В папке, куда скомпилирована наша игра, есть файл с расширением exe и папка с библиотеками куда Unity и компилирует все игровые скритпы, игровые модели и т.д. Нам понадобятся, для просмотра скрипта, всего один файл. В папке managed найдите файл Assembly-CSharp.dll
Далее скачиваем бесплатную программу ILSpy, распаковываем в удобное для нас место и запускаем программу.
Нажимаем File — Открыть и выбираем наш файл с расширением dll. Далее видим что программы декомпилировала все скрипты, которые находились в нашей игре и без труда показывает все содержимое этих скриптов. В нашем случае нам нужен скрипт timer, посмотрим на него.
Как видим, Unity не сильно то и затрудняется шифровать игровые скрипты , особо не меняет их структуру и так же, не меняет название переменных. Таким образом, есть возможность посмотреть скрипты большинства игр созданных на Unity, например скрипты игры The Long Dark без труда можно посмотреть в данной программе.
Opening existing Projects
You have several options when opening an existing Project.
In the Unity Hub, click on the Project to open it with the assigned Unity Editor version. If the Hub can’t find a matching Editor version for the Project, it displays a warning message asking you to download that version.
- Click the drop-down arrow next to the Unity Version to select a different version of the Editor. If you try to open a Project with an older version of the Editor than the one it was created in, Unity warns you that downgrading the Project might result in data loss and asks you to confirm your selection.
- Click the drop-down arrow next to the Target Platform option to select a different platform.
In the Editor, click File > Open Project to open the Hub and access the list of available Projects.
Note: For information on using Unity versions prior to 2019.1, see Starting Unity for the first time in the 2018.4 documentation.