├── .gitattributes
├── .github
└── release.yml
├── .gitignore
├── Changelog.md
├── LICENSE.md
├── README.md
├── classes.dot
├── digital-art
├── FreeBSD-wallpaper-no-text-tm.png
├── QHE-FreeBSD-Inside-Wallpaper-2024--darkmatter-titled-BlueWillowAI-assisted.png
├── QHE-FreeBSD-Inside-Wallpaper-2024-engraved-BlueWillowAI-assisted.png
├── QHE-FreeBSD-Wallpaper-2024-BlueWillowAI-assisted.png
├── QHE-FreeBSD-wallpaper-mid-text-tm.png
├── QHE-Hardened-FreeBSD-wallpaper-red-tm.png
└── Quadhelion Engineering Universal Digital Art License.md
├── docs
├── FreeBSD-Hier.pdf
└── SECURITY.md
├── harden-freebsd.py
├── images
├── harden-freebsd-logo.jpg
└── quadhelionEngineeringIcon.jpg
├── minimum.ini
├── server.ini
├── settings.ini
├── util
├── mmap_protect.c
├── pf.conf
└── robots.txt
└── vendor
└── spectre-meltdown-checker.sh
/.gitattributes:
--------------------------------------------------------------------------------
1 | spectre-meltdown-checker.sh linguist-generated=true
2 | zenbleed-workaround.csh linguist-generated=true
--------------------------------------------------------------------------------
/.github/release.yml:
--------------------------------------------------------------------------------
1 | # .github/release.yml
2 |
3 | changelog:
4 | categories:
5 | - title: Breaking Changes 🛠
6 | labels:
7 | - Semver-Major
8 | - breaking-change
9 | - title: Exciting New Features 🎉
10 | labels:
11 | - Semver-Minor
12 | - enhancement
13 | - title: Other Changes
14 | labels:
15 | - "*"
16 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .nova/Configuration.json
2 | .nova
3 | .DS_Store
4 | settings_test.ini
5 | TODO
6 | config
7 | description
8 | cloneurl
9 |
--------------------------------------------------------------------------------
/Changelog.md:
--------------------------------------------------------------------------------
1 | ## January 24, 2024
2 | * Change default umask to 027
3 |
4 | ## January 19, 2024
5 | * Enabled pf firewall by default in settings.ini
6 |
7 | ## January 17, 2024
8 | * After testing, re-introduced the Sendmail/MTA disable
9 |
10 | ## January 16, 2024
11 | **New settings**
12 | Enhanced DoS/DDoS mitigation
13 | * `net.inet6.icmp6.rediraccept = 0` to prevent ICMP attacks. Only FreeBSD as a network appliance would benefit enabling this setting.
14 | * `net.inet.tcp.drop_synfin = 1` to mitigate TCP SYN-FIN attacks and stealth probing.
15 | * `net.inet.tcp.cc.algorithm=htcp` enable TCP congestion alleviation
16 |
17 | [H-TCP](https://www.sciencedirect.com/science/article/pii/S0965997821000399#bib0017) is a congestion control protocol for high-speed and long distance networks. It uses bandwidth estimation and changes the TCP window increase/decrease parameters according to the estimated minimal and maximal bandwidth. It takes into consideration that the parameter for additive increase should be small in slower networks and should be large in high-speed and long distance networks in order to achieve fast adaptation to the available bandwidth.
18 |
19 | DoS/DDoS mitigation via network performance tuning for high-speed network servers, used by default on Vultr FreeBSD 14.0 cloud servers.
20 | * `kern.ipc.maxsockbuf=67108864`
21 | * `net.inet.tcp.sendbuf_max=67108864`
22 | * `net.inet.tcp.recvbuf_max=67108864`
23 | * `net.inet.tcp.sendbuf_auto=1`
24 | * `net.inet.tcp.recvbuf_auto=1`
25 | * `net.inet.tcp.sendbuf_inc=16384`
26 |
27 |
28 |
29 | **NOTE**
30 | * `net.inet.tcp.syncache.hashsize, cachelimit, and bucketlimit` Were last updated for 2016 Computing Hardware and should be made tunable, currently they are read-only and serve to make SYN FLOOD DoS attacks easier.
31 |
32 | ## January 8, 2024
33 | * ZenBleed workaround removed as it is now enable by default in 14 release
34 | * 32bit protections removed as FreeBSD is focusing on 64bit and in the future dropping support for 32bit
35 | * PIE, ASLR for 32bit
36 | * Sendmail limitations removed since the 14.0 MTA in use is now the more secure Dragonfly Mail Agent
37 |
38 |
39 | ---
40 |
41 | ## August 22, 2023
42 | * Removed devcpu-data-amd as the re-worked port installs both AMD and Intel with command `devcpu-data`
43 | * https://cgit.freebsd.org/ports/commit/?id=bc7829212d153aeff69b439d08e2e3001ef88ba3
44 |
45 | ## August 20, 2023
46 | * Printing clean-up
47 | * Fixed error in microcode matching
48 | * Fixed Virtual Machine vs Bare Metal c shell bug in string matching
49 |
50 | ## August 19, 2023
51 | * Zenbleed_workdaround.csh fixes
52 | * at reminder fixes
53 | * CPU Model detection fixed
54 | * AMD Threadripper Pros are still not being detected properly
55 |
56 | ## August 13, 2023
57 | * Updated to give notice that no Zenbleed affected CPU was found.
58 |
59 | ## August 11, 2023
60 | * The rc script has been updated for better performance and stability
61 | * There is no positive value cases I can find for removing the chicken-bit during operation which on the contrary may produce unexpected results as with other workarounds of this type
62 | * Rebooting without the rc script running returns the OS to an unset chicken-bit state which obviates the need to have a `rc` chicken-bit removal function.
63 | * The user chooses the workaround or not without the rc script making available CPU state changes while in operation possibly inducing kernel crashes
64 | * Simply using the `remove` argument and rebooting will return the AMD Zenbleed vulnerability -> MSR state to default
65 | * Fixed Syntax errors and word clarity in the main workaround file
66 | * Added a prompted reminder function using `at` to create a file in the home directory reminding the user to use the official patch due at that time and remove the workaround
67 | * Changed the user text notice after a microcode update for better security and stability
68 | 1. Rebooting once should show clean startup with new microcode but still keep the tools in case of reversion
69 | 2. Use the `clean` function to remove the conf directives that load the still loaded promiscuous cpu tools
70 | 3. Rebooting again to load without promiscuous cpu tools
71 |
72 | ## August 8, 2023
73 | * `settings.ini`
74 | * `microcode_update_enable` set to "YES" in preparation for Zenbleed and Downfall Updates
75 | * AMD Zenbleed mitigation script was added
76 |
77 |
78 | ## June 28, 2023
79 | * Changed requirements to be 13.1, 13.2 as this is when most security directives were added
80 | * Remove much conf syntax verification to work on all FreeBSD confs instead of just default installs
81 | * Reverted 64bit ASLR protections to 32bit since these were on by default since 13.1
82 | * `hw.mds_disable` was set at 3, AUTO
83 | * Removed `vm.pmap.pti = "1"` since this was on by default
84 |
85 |
86 | ## June 27, 2023
87 | * FreeBSD hardening script /usr/libexec/bsdinstall/hardening sets `security.bsd.allow_destructive_dtrace` is formatted improperly with the flag without quotes as in `/boot/defaults/loader.conf` and man. Script sets it properly.
88 | * Test DTrace hardening: Using all 3 commands should result in `Permission denied` or `Destructive actions not allowed`:
89 | * `dtrace -wn 'tcp:::connect-established { @[args[3]->tcps_raddr] = count(); }'`
90 | * `dtrace -wqn tick-1sec'{system("date")}'`
91 | * `dtrace -qn tick-1sec'{system("date")}'`
92 | * New setting `vm.pmap.pti = 0`
93 | * Setting `kern.securelevel` to `0` has no effect as FreeBSD will increment to 1 disallowing script execution. README changed to reflect this.
94 | * Error message conformity and clarity improvement.
95 | * Script now exits any time it restores a file to prevent partial writes and locked files.
96 | * Some sysctl.conf settings moved over to loader.conf section for better security
97 |
98 |
99 | ## June 23, 2023
100 | * 64bit ASLR setting was reverted back to 32bit enable as 64bit is enabled by default.
101 | * `kern.randompid` works better if the number is manually set over 100 and is a prime [(*)](https://reviews.freebsd.org/transactions/detail/PHID-XACT-DREV-76pds6dxlcy5er6/)
102 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | # Quadhelion Engineering Universal Software License
2 |
3 | [URL](https://www.quadhelion.engineering/qhelp.html)
4 |
5 | ## QHELP-OME-NC-ND-HI
6 |
7 | **Legend:**
8 |
9 | * (Q)had(H)elion(E)ngineering (L)icense (P)ermission
10 | * (O)btain (M)odify (E)xecute
11 | * (N)on-(C)ommercial
12 | * (N)o (D)erivatives
13 | * (H)uman (I)ntelligence
14 |
15 | All entities are Universally bound by the terms and conditions of this license as it is inseparable to the Software using this license. This license grants no other rights than detailed herein.
16 |
17 |
18 |
19 | ## Executive Summary
20 |
21 | Non-Commercial usage, retain and forward author and license data. Modify existing code as needed up to 25% while allowing unlimited new additions. The Software may use or be used by other software.
22 |
23 |
24 |
25 | ### Section 1 – Definitions.
26 |
27 | * **Universal** is defined as all the states of existence. If exists, this License applies.
28 | * **Software** is defined as means used to produce a desired result on a calculating device accompanying and referencing this License.
29 | * **Creator** is defined as the natural human being that created the Software here designed in his mind and written down to Obtain and Execute.
30 | * **License** is defined as what all entities other than the Creator of the Software allows to be done with the software.
31 | * **Licensee** is defined as all entities other than the Creator of the Software.
32 | * **Obtain** is defined as having knowledge of the means used in the Software.
33 | * **Modify** is defined as making changes to the Execution of the Software in conformance with the existing Execution process in majority, utilizing the same data types of input and output originally used by the Software, retaining the intended use of the Execution of the Software in superset of subset of solutions, workflows, processing, intake, and production in general, but not in detail.
34 | * **Execute** is defined as having a calculating device calculate the Software.
35 | * **Intelligence** is defined as having the ability to solve complex problems with judgement.
36 | * **Human** is defined as Homo sapiens birthed from another living Female Homo sapiens.
37 |
38 |
39 |
40 | ### Section 2 - Software Modification Allowance
41 |
42 | The software **may not** be modified in the following ways:
43 |
44 | * The Software logic itself cannot be changed *in majority*.
45 | * The original *application* to which the Software *was applied* cannot be modified.
46 | * Changing or replacing of **more than 25%** of the existing programming code of the Software is **not allowed**. This does not include error handling, metadata or comments.
47 | * Programming language comments cannot be modified.
48 | * Metadata cannot be modified.
49 | * Author and License information cannot be modified.
50 | * You may not adapt, translate, reverse engineer, decompile, disassemble, or otherwise reuse the Software code, Software logic, or logic designs of the Software.
51 | * The Software may not be re-created or re-generated in whole or in part in another programming language or by any means except by permission of the Creator.
52 |
53 | **The Software may be modified in the following ways:**
54 |
55 | 1. Any modification must retain the majority of functionality in conformance with the original Software.
56 | 2. The Software can only be modified with the original programming language it was written in.
57 | 3. The Software may be used by other software. The Software may use other software.
58 | 4. Allowance of additional new programming code and comments to the Software is unlimited.
59 |
60 | **Examples of how the Software may be modified:.**
61 |
62 | 1. The application of the Software is the computer systems and components to which the Software originally Executed; that being the data, systems, processes, inputs and outputs, and categories or types of computers, systems, data, I/O, and components the Software interacts with upon Execution.
63 | 1. For example, if the Software Executes outputing Firewall rules and reloading those rules in a Firewall than it is not allowed to modify this Software to simply produce files that are distributed on FTP.
64 | 1. Removing a Software function of only two functions is not majority conformance.
65 | 2. Unlimited new functions and functionality can be added.
66 | 3. Software logic can be changed without removing the majority of functions or functionality.
67 |
68 |
69 |
70 | ### Section 3 – Scope.
71 |
72 | **License granted.**
73 |
74 | Subject to the terms and conditions of this License, the Creator hereby grants the following exclusive entities permission to Execute the Software which meet both the following conditions:
75 |
76 | 1. Natural Human Beings
77 | 1. Genus and Species commonly classified as *Homo Sapiens*, born on the same known world terra firma as the Creator was born on, being birthed by a Female Natural Human Being.
78 | 2. Non-Commercial Entities
79 | 1. Entities who are not profit motivated and are not substantially valued.
80 | 2. All Corporations type Limited Liability Company (LLC), S-Corporation (S-Corp), and C-Corporation (C-Corp) are strictly forbidden from Software Obtainment and Execution and cannot be a Licensee.
81 |
82 |
83 |
84 | **License denied.**
85 |
86 | 1. Non-Human Intelligences such as Artificial Intelligence, Generative, Language Models, or Generated Intelligences have no permissions to Obtain, Modify or Execute.
87 | 1. Any computational analysis or automata characterized as Intelligence has no allowance or License to Obtain, Modify, or Execute the Software.
88 | 2. Any sentience that was not birthed from a living Female Human Being has no allowance or License to Obtain, Modify, or Execute the Software.
89 | 2. Patents, Trademarks, Copyrights, and legal or financial instruments, or applications to the Software, it's Execution, or it's License thereof is strictly prohibited.
90 | 3. Derivations, re-creations, re-generations, and adaptations of the Software are strictly prohibited.
91 | 4. Effective technological measures, Effective protective technological measures, and any prevention or limitation placed on the exercise of the Licensee's Execution of the Software is strictly prohibited.
92 |
93 |
94 |
95 | **Licensor.**
96 |
97 | This words and expressions of allowance and denial contained are here the License which in totality and in summary the whole of this formatted document is itself the Licensor. Adhering to the provisions of this License constitutes a Licensee. The Creator himself is not the Licensor and is not in contract in any way with any entity.
98 |
99 |
100 |
101 | ### Section 4 – License Conditions.
102 |
103 | Your exercise of the Licensed Rights is expressly made subject to the following conditions.
104 |
105 | The Licensee must:
106 |
107 | 1. **Retain** the License, usually the file LICENSE.md, with the Software.
108 | 1. All information contained in the Software referring to the License and Identity of the Creator.
109 | 2. All Author information including URLs, dates, emails, must be retained.
110 | 3. This License file must be maintained at all times alongside the Software.
111 |
112 | 2. **Indicate** the Licensed Software is licensed under this License
113 | 1. Include the text of, the file of, or the URI or hyperlink to, this License, *pertinent* to any entity that is not aware of this Copyright, Trademark, Patent, or, License, of this Software.
114 | 2. This includes requests, audits, inspection, or reviews in singular or in totality of all Software used on the Calculating Device where the Software resides, referenced, or Executed;
115 | 3. The Licensee must make aware this License to all interested entities in the Software, it's means, functions, or results.
116 | 3. **Obtain, Customize, and Execute** the Software in conformance with this License.
117 |
118 |
119 |
120 | ### Section 5 – Disclaimer of Warranties and Limitation of Liability.
121 |
122 | Unless otherwise separately undertaken by the Creator, to the extent possible, the Creator offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Software, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to the Licensee.
123 |
124 | To the extent possible, in no event will the Creator be liable to the Licensee on any legal basis or theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this License or use of the Licensed Software, even if the Creator has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to the Licensee.
125 |
126 | The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
127 |
128 |
129 |
130 | ### Section 6 – Associated files.
131 |
132 | Images and Digital Art obtained along with the Software are original works and automatically under International Copyright Law and may not be altered or distributed. Document files are original works under full Copyright of the Creator.
133 |
134 |
135 |
136 | ### Section 7 – Term and Termination.
137 |
138 | If the Licensee or any entity fails to comply with this License, then the Licensee's and entities rights under this License terminate automatically and immediately.
139 |
140 |
141 |
142 | ### Section 8 – Other Terms and Conditions.
143 |
144 | The Creator is not himself bound by these terms and conditions, allowances and denials, or any additional or different terms or conditions.
145 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Harden FreeBSD
2 |
3 | 
4 |
5 | _Table of Contents_
6 |
7 | * [New Features](#New)
8 | * [Additional Features](#Additional)
9 | * [Installation](#Installation)
10 | * [Customization](#Customization)
11 | * [Settings Used](#Descriptors)
12 | * [License](#License)
13 | ---
14 |
15 | FreeBSD officially defaults to [Permanently Insecure Mode](https://man.freebsd.org/cgi/man.cgi?query=security&sektion=7&manpath=freebsd-release#SECURING_THE_KERNEL_CORE,_RAW_DEVICES,_AND_FILE_SYSTEMS). This script will duplicate all the hardening settings run by `/usr/libexec/bsdinstall/hardening` and much more. Any directive can be set and re-set with a customizable `settings.ini` for administering, tuning, and easier jail management. All existing entries in all confs will remain untouched unless they are modified in the settings file.
16 |
17 | This script is also targeted to new users of FreeBSD so that they may leverage years of security contributions by the entire BSD community across all spectra, implemented on their system in seconds.
18 |
19 | Each of the security settings was researched, assessed, and chosen as a set of mitigations for maximizing threat reduction while minimizing restriction of system capability and availability.
20 |
21 | ---
22 |
23 | For a more comprehensive true "hardened" solution with more security than this repo scope, which involves kernel modifications, I refer you to [HardenedBSD](https://hardenedbsd.org).
24 |
25 | ---
26 |
27 | ## Main Features
28 |
29 | * Makes backups of `rc.conf`, `sysctl.conf`, `login.conf`, and `loader.conf` on first run
30 | * Disables Sendmail service, but it can still be run by command and abused.
31 | * **Recommend**:
32 | * `rm -rf /usr/libexec/sendmail /usr/libexec/dma` OR `chmod -R 000 sendmail dma`
33 | * `pkg install opensmtpd`
34 | * Sets passwords to blowfish encryption, which **is** better than SHA512 for this purpose
35 | * [Okta Medical Device Authentication](https://auth0.com/blog/hashing-in-action-understanding-bcrypt/)
36 | * [Security Stack Exchange](https://security.stackexchange.com/questions/133239/what-is-the-specific-reason-to-prefer-bcrypt-or-pbkdf2-over-sha256-crypt-in-pass)
37 | * [Silver Stripe, Census Gov Contrator](https://docs.silverstripe.org/en/5/developer_guides/security/secure_coding/)
38 | * [Google Engineer Gregory Gains](https://www.gregorygaines.com/blog/how-to-hash-and-salt-passwords-in-golang-using-sha512-and-why-you-shouldnt/)
39 | * Sets passwords to expire at 120 days
40 | * Removes `other` write permissions from key system files and folders
41 | * Allows only root for `cron` and `at`
42 | * Primitive flag verification catches simple errors
43 | * Modularizable within other tools
44 | * Automate any shell command
45 | * System Logging to `/var/log/messages` and Script Logging to `/var/log/harden-freebsd.log`
46 | * Pretty prints color output of script execution to console while running
47 | * Sets umask to 027
48 |
49 | ---
50 |
51 |
52 | ### Includes
53 | * Desktop Wallpapers as a special gift to users of the Software
54 | * Directory (Hier)archy Visual Map, PDF, in /docs
55 | * robots.txt to deny AI use of your intellectual property, with inline `nginx.conf` format and commented section for use as a plain txt file
56 | * Robust firewall settings for pf
57 | * You can grab icons and more Wallpapers at the [Quadhelion Engineering Development Gogs/Gitea Git Repo](https://quadhelion.dev/elias/bsd-wallpapers)
58 |
59 | ---
60 |
61 |
62 | ### New Features in 3.1
63 | * A package audit is automatically run identifying vulnerabilities in installed packages and saves to file `pkg-audit-report`
64 | * Security Tiering has been introduced with additional settings files minimal and server
65 | * A script argument can be given naming the settings ini file you wish to use, mainly to toggle between secure and minimal, otherwise settings.ini is used
66 | * A minimum security and high performance server tier ini files are now included
67 | * Adjust as neccessary or make your own set
68 | * A script argument of "restore" is now available, overwriting the changed files with the original files saved during first run
69 | * rc.conf, sysctl.conf, and loader.conf are restored. `login.conf` and the password changes are not reversed, neither are file permissions or at, cron adjustments
70 | * `minimum.ini` does not have `first_run = True` set as it is expected to usually run secure. Therefore if using this ini file first, **backups will not be made**.
71 | * New wallpapers have been added with the assistance of [LimeWire BlueWillow v4](https://limewire.com/features/bluewillow-ai) Artificial Intelligence image generator.
72 | * Change the default umask to 027
73 | ---
74 |
75 |
76 | ## Known Incompatibilities (Insecure) 09/7/2023
77 | * **VM**:
78 | * VirtualBox Shared Folders
79 | * **Workstation**:
80 | * **Firefox, Chromium** explicitly use [shared memory](https://www.usna.edu/Users/cs/crabbe/SI411/current/security/memory.html) allowing data access between private and non-private windows, tabs as well as other currently running apps.
81 | * Conflicts with `kern.elf64.allow_wx`
82 | * Linux Binary Compatibility
83 | * **Server**: Nginx
84 |
85 |
86 | ### Verified Compatible
87 | * **Workstation**:
88 | * Librewolf, Qutebrowser, Transmission, Evolution, RhythmBox, VLC, Abiword, Gimp, Inkscape, Spacemacs, Git
89 | * **Server**:
90 | * Apache (w/o memcache), OpenSMTPD, MariaDB `have_dynamic_loading=YES` (with plugins)
91 |
92 |
93 | ---
94 |
95 |
96 | ## FreeBSD Security Advisories
97 | https://www.freebsd.org/security/advisories/
98 |
99 | **FreeBSD Update Procedure**
100 |
101 | ```
102 | root@freebsd:~# freebsd-update fetch
103 | root@freebsd:~# freebsd-update install
104 | root@freebsd:~# shutdown -r +10min "Rebooting for a security update"
105 | ```
106 |
107 | ---
108 |
109 | ### FreeBSD 14.0 Security Changes
110 | * New [Mitigations Manual](https://man.freebsd.org/cgi/man.cgi?query=mitigations&sektion=7&format=html)
111 | * New Kernel Address Sanitizer
112 | * [KASAN](https://man.freebsd.org/cgi/man.cgi?query=kasan&sektion=9&format=html) is a subsystem which leverages compiler instrumentation to detect invalid memory accesses in the kernel.
113 | * The **Zenbleed bug affecting AMD Zen2 processors is now automatically mitigated** (via chicken bit), preventing misbehavior and data leaks on affected machines. If needed, applying the mitigation can be manually controlled via the machdep.mitigations.zenbleed.enable sysctl(8) knob. Please consult the new [mitigations(7)](https://man.freebsd.org/cgi/man.cgi?query=mitigations&sektion=7&format=html) manual page for more information.
114 | * Position Independent Executable (PIE) support enabled by default on x64
115 | * Address Space Layout Randomization (ASLR) is enabled by default on x64
116 | * To disable for a single invocation, use the [proccontrol(1)](https://man.freebsd.org/cgi/man.cgi?query=proccontrol&sektion=1&format=html) command: `proccontrol -m aslr -s disable command.`
117 | * To disable ASLR for all invocations of a binary, use the [elfctl(1)](https://man.freebsd.org/cgi/man.cgi?query=elfctl&sektion=1&format=html) command: `elfctl -e +noaslr file`
118 | * A workaround has been implemented for a hardware page invalidation problem on Intel Alder Lake (twelfth generation) and Raptor Lake (thirteenth generation) hybrid CPUs.
119 | * The default mail transport agent (MTA) is now the Dragonfly Mail Agent.
120 | * Support has been added to the kernel crypto for the XChaCha20-Poly1035 AEAD cipher.
121 | * The process visibility policy controlled by the `security.bsd.see_jail_proc` sysctl(8) knob was hardened.
122 | * The process visibility policy controlled by the `security.bsd.see_other_gids` sysctl(8) knob was fixed to consider the real group of a process instead of its effective group when determining whether the user trying to access the process is a member of one of the process' groups.
123 |
124 | ---
125 |
126 |
127 | ## Additional Software
128 |
129 | * Scripts included to verify the implementation. Run before and after the hardening.
130 | * Kernel vulnerability diagnosis provided by [Stéphane Lesimple's](https://github.com/speed47) spectre-meltdown-checker
131 | * `cd vendor`
132 | * `chmod 750 spectre-meltdown-checker.sh`
133 | * `sudo ./spectre-meltdown-checker.sh`
134 | * You should only be left with the MCEPSC, Machine Check Exception on Page Size Change Vulnerability, [CVE-2018-12207](https://www.freebsd.org/security/advisories/FreeBSD-SA-19:25.mcepsc.asc)
135 | * MMAP, MProtect vulnerability diagnosis provided by [u/zabolekar](https://www.reddit.com/r/BSD/comments/10isrl3/notes_about_mmap_mprotect_and_wx_on_different_bsd/)
136 | * `cd util`
137 | * `cc mmap_protect.c`
138 | * `./a.out`
139 | * You should have two successes
140 |
141 | ---
142 |
143 |
144 | ---
145 | # Main Details
146 |
147 | ## Requirements
148 | * FreeBSD 14.0
149 | * Python 3.9.16
150 |
151 |
152 |
153 | ## Installation
154 |
155 | **WARNING: Once kernel level 1 is set by this script, you will not be able to modify these confs again with this script until it is set to -1 and rebooted!**
156 |
157 | * Set `kernlevel = -1` if you want to test various setting groups with your applications and network
158 | * Customize `settings.ini` to whatever is needed, the script will change the directive to your flag
159 | * Set permissions `chmod 750 harden-freebsd.py` to prevent shell injection from another account or process
160 | * Set permissions `chmod 640 settings.ini` to prevent shell injection from another account or process
161 | * No `settings.ini` section can be entirely commented out nor be completely empty
162 | * `sudo ./harden-freebsd.py`
163 |
164 |
165 | ## Conf File Verification
166 |
167 | `kern.vty = "vt"`
168 |
169 | This script does primitive verification of the confs flags in strict accordance with system man. Many online tutorials even on the FreeBSD family of websites do not use the proper syntax. Check the log for any validation failures. Use proper syntax, remove the syntax checking lines 241-261, or rewrite the regular expression to make a new check suitable for you.
170 |
171 | * For `/etc/sysctl.conf` the script checks for no quotes
172 | * For `/boot/loader.conf` the script strictly verifies syntax from man and `/boot/defaults/loader.conf` syntax
173 | * All directives in these sister confs must be in quotes
174 |
175 | If you do get stuck in read-only single-user mode and need to correct a configuration file then use:
176 |
177 | ```sh
178 | zfs set readonly=false zroot
179 | zfs mount -a
180 | ```
181 |
182 |
183 | ## Customization
184 |
185 | #### pf.conf
186 | pf is now enabled in `settings.ini` by default but not in `minimal.ini` or `server.ini`. You will need to edit the macros with your interface, SSH port, and IP addresses before use. `admin_ips` is used by default and will take a list of two IP Addresses seperated by a space, `admin_ip_range` is included for convenience. If you will be using the range macro instead of the default make sure to edit line 108 changing `admin_ips` to `admin_ip_range`. Redis is configured to be localhost only.
187 |
188 |
189 | #### Backups
190 |
191 | The very first time the script is run it will make copies of `rc.conf`, `sysctl.conf`, `login.conf`, and `loader.conf` named `rc.conf.original` etc. If you've already done this yourself you may want to rename or move those files. After the script is once run, it sets that field to false and no longer makes backups. If you would like you can set `settings.ini` section `[SCRIPT]`option `first_run` to `True` with capital `T` to make new backups at any time after you've renamed the original backups or the script will overwrite them.
192 |
193 |
194 | #### Chmod-ability
195 |
196 | The set of files needed to be secure changed and changed throughout testing and so it ended up as a shell command but an error checked function was provided for the administrator programmer to use instead of appending to the long list in `settings.ini` section `[FILESEC]` if you wish or to work with other software.
197 |
198 | Those files are:
199 |
200 | `etc/ftpusers /etc/group /etc/hosts /etc/hosts.allow /etc/hosts.equiv /etc/hosts.lpd /etc/inetd.conf /etc/login.access /etc/login.conf /etc/newsyslog.conf /etc/rc.conf /etc/ssh/sshd_config /etc/sysctl.conf etc/syslog.conf /etc/ttys /etc/crontab /usr/bin/crontab /usr/bin/at /usr/bin/atq /usr/bin/atrm /usr/bin/batch /var/log`
201 |
202 | #### Secure Password Settings
203 |
204 | The newly applied settings will not take effect until you reset your password.
205 |
206 | ---
207 |
208 |
209 |
210 |
211 | # Setting Descriptors
212 | **Startup**
213 |
214 | * `kern_securelevel_enable = "YES"`
215 | * Enable access to other than permanently insecure modes
216 | * `microcode_update_enable = "YES"`
217 | * Allow CPU microcode/firmware updates
218 | * Disable Mail Transport Agent
219 | * Despite the documentation saying "NONE" is deprecated, this is not the case and hasn't been for over 15 years.
220 | * These are *thoroughly* tested as the best settings as "NONE" produces one less WARNING than "NO" in some cases.
221 | * `syslogd_flags="-ss"`
222 | * Disallow syslogd to bind to a network socket
223 | * `clear_tmp_enable = "YES"`
224 | * Clear the /tmp directory on reboot
225 | * `icmp_drop_redirect="YES"`
226 | * Disallow redirection of ICMP (ping, echo)
227 | * `inetd_enable = "NO"`
228 | * Disallow Network File System to share directories over the network
229 | * `portmap_enable = "NO"`
230 | * Disallow portmapping since Network File Systems is disallowed
231 | * `update_motd = "NO"`
232 | * Disallow computer system details from being added to /etc/motd on system reboot
233 |
234 | **System**
235 |
236 | * `kern.securelevel = 1` [(*)](https://man.freebsd.org/cgi/man.cgi?securelevel)
237 | * The system immutable and system append-only flags may
238 | not be turned off; disks for mounted file systems, /dev/mem and
239 | /dev/kmem may not be opened for writing; /dev/io (if your platform
240 | has it) may not be opened at all; kernel modules (see kld(4)) may
241 | not be loaded or unloaded. The kernel debugger may not be entered
242 | using the debug.kdb.enter sysctl. A panic or trap cannot be forced
243 | using the debug.kdb.panic, debug.kdb.panic_str and other sysctl's.
244 | * `security.bsd.see_other_uids = 0`
245 | * Disallow users from seeing information about processes that are being run by another user (UID)
246 | * `security.bsd.see_other_gids = 0` [(*)](https://docs.freebsd.org/en/books/handbook/mac/#mac-policies)
247 | * Disallow users from seeing information about processes that are being run by another group (GID)
248 | * `security.bsd.see_jail_proc = 0` (Sysctl MIB Entry `sysctl -a | grep security.bsd`)
249 | * Disallow non-root users from seeing processes in jail
250 | * `security.bsd.unprivileged_read_msgbuf = 0` (Sysctl MIB Entry `sysctl -a | grep security.bsd`)
251 | * Disallow non-root users from reading system message buffer
252 | * `kern.randompid = 107` [(*)](https://wiki.freebsd.org/DevSummit/201308/Security)
253 | * Force kernel to randomize process ID's using above salt value instead of sequential
254 | * `net.inet.ip.random_id = 1`
255 | * Randomize IP packet ID
256 | * `net.inet.ip.redirect = 0`
257 | * Disallow ICMP host redirects
258 | * `net.inet.tcp.always_keepalive = 0`
259 | * Disallow keeping open idle TCP connections. This may need to be changed if you are serving
260 | * `net.inet.tcp.blackhole = 2` +(UDP)[(*)](https://man.freebsd.org/cgi/man.cgi?query=blackhole)
261 | * Packets that are received on a closed port will not initiate a reply
262 | * `net.inet.tcp.path_mtu_discovery = 0` [(*)](https://man.freebsd.org/cgi/man.cgi?query=tcp&sektion=4)
263 | * Disallows TCP to determine the minimum MTU size on any network that is currently in the path between two hosts
264 | * `net.inet.icmp.drop_redirect = 1`
265 | * Pairs with rc.conf startup, as once enabled, it is then set
266 | * `net.inet6.icmp6.rediraccept = 0`
267 | * Disable ping IPv6 redirection mitigating ICMP attacks
268 | * Set to 1 if using FreeBSD as network appliance
269 | * `net.inet.tcp.drop_synfin` [(*)](https://www.juniper.net/documentation/us/en/software/ccfips22.2/cc-security_srx5000/cc-security/topics/task/configuring-tcp-syn-fin-attack.html)
270 | * Mitigates probe scans and has positive impact against DoS/DDoS attacks
271 | * Quadhelion Engineering [Research](https://www.quadhelion.engineering/articles/freebsd-synfin.html) on this setting
272 | * `hw.mds_disable = 3` [(*)](https://www.kernel.org/doc./html/latest/arch/x86/mds.html)
273 | * Enable Microarchitectural Data Sampling Mitigation version `VERW`
274 | * Change value to `3` (AUTO) if using a Hypervisor without MDS Patch
275 | * `hw.spec_store_bypass_disable = 1` [(*)](https://handwiki.org/wiki/Speculative_Store_Bypass)
276 | * Disallow Speculative Bypass used by Spectre and Meltdown
277 | * `kern.elf64.allow_wx = 0` [(*)](https://www.ibm.com/docs/en/aix/7.2?topic=memory-understanding-mapping)
278 | * Disallow write and execute for shared memory
279 |
280 | **server.ini**
281 |
282 | Common network tuning values to increase performance and alleviate congestion, useful against DoS/DDoS attacks on high bandwidth application servers
283 |
284 | * `kern.ipc.maxsockbuf=67108864`
285 | * `net.inet.tcp.sendbuf_max=67108864`
286 | * `net.inet.tcp.recvbuf_max=67108864`
287 | * `net.inet.tcp.sendbuf_auto=1`
288 | * `net.inet.tcp.recvbuf_auto=1`
289 | * `net.inet.tcp.sendbuf_inc=16384`
290 |
291 |
292 | **Kernel**
293 | * `security.bsd.allow_destructive_dtrace = "0"`
294 | * Disallow DTrace to terminate processes
295 | * Test DTrace hardening: Using all 3 commands should result in `Permission denied` or `Destructive actions not allowed`:
296 | * `dtrace -wn 'tcp:::connect-established { @[args[3]->tcps_raddr] = count(); }'`
297 | * `dtrace -wqn tick-1sec'{system("date")}'`
298 | * `dtrace -qn tick-1sec'{system("date")}'`
299 | * `hw.ibrs_disable = "3"` [(*)](https://wiki.freebsd.org/SpeculativeExecutionVulnerabilities)
300 | * Prevent Spectre and Meltdown CPU Vulnerabilities, 3 for AUTO
301 |
302 |
303 | ---
304 |
305 | ### January 17, 2024 Changelog
306 | *If you are on FreeBSD 13.2 download the 3.0.1 release tag*
307 |
308 | * pf enabled by default
309 | * ZenBleed workaround removed
310 | * 32bit protections removed
311 |
312 |
313 | ---
314 |
315 |
316 | *Full [Changelog](Changelog.md)*
317 |
318 |
319 | ---
320 |
321 |
322 |
323 | ## License Summary
324 |
325 | ### Software
326 | Non-Commercial usage, Human Intelligence only, retain and forward author and license data. Modify existing code as needed up to 25% while allowing unlimited new additions. The Software may use or be used by other software.
327 |
328 |
329 | ### Digital Art
330 | All Digital Artists and Original Digital Art automatically receives robust International Copyright protections.
331 | * Supplemental License [here](digital%20art/Quadhelion%20Engineering%20Universal%20Digital%20Art%20License.md)
332 | * QHE Wallpapers meet the [FreeBSD Foundation Trademark Usage Terms and Conditions](https://freebsdfoundation.org/legal/trademark-usage-terms-and-conditions/) where most FreeBSD digital art does not.
333 | * An original digital art creation containing the FreeBSD Logo under T&C, the larger work is thus automatically copyrighted worldwide and may not be distributed, shared, or altered.
334 | * FreeBSD Foundation Members, Employees, and Associates are exempt from Digital Art restrictions.
335 |
336 |
337 |
338 | ## Security Guidelines
339 |
340 | Since this Software uses shell commands it is required to place it in a secure directory with permissions on the **parent** directory to have no permissions for `other` /all/world group to write or *execute* and **no network access**.
341 |
342 | Please follow [these guidelines](/docs/SECURITY.md) should you find a vulnerability not addressed in the audit.
343 |
344 |
345 | ## Statement of Security:
346 |
347 | * **Risk** - Low
348 | * **Impact** - Medium
349 |
350 | This script has no networking, accesses no sockets, and uses only standard libraries.
351 |
352 | Although this script is using `subprocess.run(shell=True)` the only possibility of shell injection is from the paths customized by the Licensee or unauthorized access to the filesystem the script resides on in order to perform unauthorized modifications to `settings.ini`or the Software which is not a vulnerability of the Software.
353 |
354 |
355 | ### Latest Development Version
356 |
357 | [Quadhelion Engineering Code Repository](https://quadhelion.dev)
358 |
359 |
360 |
361 | 
362 |
--------------------------------------------------------------------------------
/classes.dot:
--------------------------------------------------------------------------------
1 | digraph "classes" {
2 | rankdir=BT
3 | charset="utf-8"
4 | "harden-freebsd.Conf" [color="black", fontcolor="black", label=<{Conf|file
flag
found : bool
setting
|addConf()
checkConf(): bool
restoreConf()
setConf()
verifyConf()
}>, shape="record", style="solid"];
5 | "harden-freebsd.SetOpts" [color="black", fontcolor="black", label=<{SetOpts|section
|}>, shape="record", style="solid"];
6 | }
7 |
--------------------------------------------------------------------------------
/digital-art/FreeBSD-wallpaper-no-text-tm.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wravoc/harden-freebsd/beef6365d0a15a7315dcfd541302ca6152d26f9b/digital-art/FreeBSD-wallpaper-no-text-tm.png
--------------------------------------------------------------------------------
/digital-art/QHE-FreeBSD-Inside-Wallpaper-2024--darkmatter-titled-BlueWillowAI-assisted.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wravoc/harden-freebsd/beef6365d0a15a7315dcfd541302ca6152d26f9b/digital-art/QHE-FreeBSD-Inside-Wallpaper-2024--darkmatter-titled-BlueWillowAI-assisted.png
--------------------------------------------------------------------------------
/digital-art/QHE-FreeBSD-Inside-Wallpaper-2024-engraved-BlueWillowAI-assisted.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wravoc/harden-freebsd/beef6365d0a15a7315dcfd541302ca6152d26f9b/digital-art/QHE-FreeBSD-Inside-Wallpaper-2024-engraved-BlueWillowAI-assisted.png
--------------------------------------------------------------------------------
/digital-art/QHE-FreeBSD-Wallpaper-2024-BlueWillowAI-assisted.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wravoc/harden-freebsd/beef6365d0a15a7315dcfd541302ca6152d26f9b/digital-art/QHE-FreeBSD-Wallpaper-2024-BlueWillowAI-assisted.png
--------------------------------------------------------------------------------
/digital-art/QHE-FreeBSD-wallpaper-mid-text-tm.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wravoc/harden-freebsd/beef6365d0a15a7315dcfd541302ca6152d26f9b/digital-art/QHE-FreeBSD-wallpaper-mid-text-tm.png
--------------------------------------------------------------------------------
/digital-art/QHE-Hardened-FreeBSD-wallpaper-red-tm.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wravoc/harden-freebsd/beef6365d0a15a7315dcfd541302ca6152d26f9b/digital-art/QHE-Hardened-FreeBSD-wallpaper-red-tm.png
--------------------------------------------------------------------------------
/digital-art/Quadhelion Engineering Universal Digital Art License.md:
--------------------------------------------------------------------------------
1 | # Quadhelion Engineering Universal Digital Art License
2 |
3 |
4 |
5 | ## QHEUDAL-NC-NA-ND
6 |
7 | **Legend:**
8 |
9 | * (Q)had(H)elion (E)ngineering (U)niversal (D)igital (A)rt (L)icense
10 | * (N)on-(C)ommercial
11 | * (N)o Alterations
12 | * (N)o Distribution
13 |
14 |
15 |
16 | ## Executive Summary
17 |
18 | Original Digital Art creation even if containing other permitted use material is automatically copyrighted in the United States of America and most of the world under International Law. All digital art may not be shared in any way with others. The QHE watermark is not to be removed, hidden, nor the aspect ratio changed.
19 |
20 |
21 |
22 | ## Allowance
23 |
24 | * Licencees of the Software who have at least once executed the Software while meeting the License requirements may use copies of the digital art on any personal computer, personal Virtual Machine, or personal device.
25 |
26 | * FreeBSD Foundation Members, Employees, and Associates are exempt from these restrictions
27 |
28 | ## Restrictions
29 |
30 | The original author of this digital art creations, Elias Christopher Griffin, via Quadhelion Engineering, sets forth the following restrictions on his art.
31 |
32 | **Non-Commercial**
33 | No gain is to be made through the use of the digital art and is strictly forbidden for use in a Commercial act.
34 |
35 | **No Alterations**
36 | The content, display, and file of the digital art may not be modified in any way excepting display adjustment on a personal device using system wallpaper tools. The file can never be altered in it's aspect ratio, cropped by a tool, overlayed, or combined with any other art, image, or text.
37 |
38 | **No Distributions**
39 | The digital art is to be used by Licensees of the Software in which it was intended and originally accompanied. It may not be distributed, re-distributed, shared, or put on the internet or any communications platform.
40 |
41 | ## Full Restrictions
42 |
43 | **Logo, Icons, and Software Art**
44 | No one but the creator may use the Quadhelion Engineering Logo, digital art associated with the Software itself, or the Software repository art.
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/docs/FreeBSD-Hier.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wravoc/harden-freebsd/beef6365d0a15a7315dcfd541302ca6152d26f9b/docs/FreeBSD-Hier.pdf
--------------------------------------------------------------------------------
/docs/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Security Policy
2 |
3 |
4 |
5 | ## Report a Vulnerability
6 |
7 | 1. Open a Github Private Vulnerability Report for "Wravoc" using the "Security" Tab on the home page of the repository following [best practices](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing/best-practices-for-writing-repository-security-advisories). Click **Report a vulnerability** to open the advisory form.
8 | 2. If you believe this vulnerability is severe or wish to send files please email [elias@quadhelion.engineering](mailto:elias@quadhelion.engineering) expecting a reply within 48 hours.
9 |
10 |
11 |
12 | ## How to report a vulnerability
13 |
14 | Please include:
15 |
16 | * Your Operating System details including:
17 |
18 | * Who was file system owner of the Software
19 | * What were the file system permissions on the Software
20 | * What networking processes had access to that file
21 | * What command was used to Execute the Software
22 | * Where the Software was located when it was Executed
23 |
24 | * Your Python Environment Details including:
25 |
26 | * PDB output
27 |
28 | * `python3 -m pdb authlog-threats.py`
29 |
30 | * What modules were loaded at the time the Software was Executed
31 |
32 | * ```
33 | import sys
34 | import pprint
35 |
36 | # pretty print loaded modules
37 | pprint.pprint(sys.modules)
38 | ```
39 |
40 | * Version
41 |
42 | * Automations
43 |
44 | * Including automatic Python repository, pip, or relevant software updating
45 |
46 | * Other Python scripts that had access to the Software
47 |
48 | * What customizations you used in the Software
49 |
50 | * Thorough details of vulnerability exploit
51 |
52 | * What process was used to prove the exploit
53 | * What files were touched
54 | * Relevant shell history during the process
55 | * Relevant sections of logs detailing this outcome
56 | * Screenshots of all the above
57 | * The hash and file size of the Software
58 |
59 |
60 |
61 |
62 | ## Confidentiality
63 |
64 | Do not publically post information on how to utilize the vulnerability or details which others may find able to utilize the vulnerablity.
--------------------------------------------------------------------------------
/harden-freebsd.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | """
4 | Harden FreeBSD system perms, settings.
5 | Set and reset rc, sysctl, login, confs; set file perms, run shell commands
6 | Uses ini file in the same directory.
7 |
8 | Usage:
9 | ./harden-freebsd.py
10 | ./harden-freebsd.py
11 | ./harden-freebsd.py restore
12 | """
13 |
14 | __author__ = "Elias Christopher Griffin"
15 | __url__ = "https://www.quadhelion.engineering"
16 | __license__ = "QHELP-OME-NC-ND-HI"
17 | __copyright__ = "https://www.quadhelion.engineering/qhelp.html"
18 | __version__ = "3.1"
19 | __date__ = "01/20/2024"
20 | __email__ = "elias@quadhelion.engineering"
21 | __status__ = "Production"
22 |
23 |
24 |
25 | from pathlib import Path
26 | from datetime import datetime
27 | import os, re, subprocess, syslog, configparser, shutil, sys
28 |
29 | _date = datetime.now()
30 | date_time = _date.strftime("%m/%d/%Y, %H:%M")
31 |
32 |
33 | # Setup for script argument processing
34 | sysargs = sys.argv
35 | config = configparser.ConfigParser()
36 |
37 |
38 | # Setup to manipulate all the system files
39 | harden_freebsd_log = Path("/var/log/harden-freebsd.log")
40 | rc_conf = Path("/etc/rc.conf")
41 | sysctl_conf = Path("/etc/sysctl.conf")
42 | loader_conf = Path("/boot/loader.conf")
43 | login_conf = Path("/etc/login.conf")
44 | cron_access = Path("/var/cron/allow")
45 | at_access = Path("/var/at/at.allow")
46 |
47 |
48 | # Set the backup file names
49 | backup_suffix = ".original"
50 | rc_backup = rc_conf.with_name(rc_conf.name + backup_suffix)
51 | sysctl_backup = sysctl_conf.with_name(sysctl_conf.name + backup_suffix)
52 | loader_backup = loader_conf.with_name(loader_conf.name + backup_suffix)
53 | login_backup = login_conf.with_name(login_conf.name + backup_suffix)
54 |
55 |
56 | # Handle script arguments
57 | sysargs = sys.argv
58 | config = configparser.ConfigParser()
59 |
60 | if len(sys.argv) == 2:
61 | script_argument = sys.argv[1]
62 | script_argument_path = Path(script_argument)
63 | if script_argument_path.exists and script_argument_path.suffix == ".ini":
64 | config.read(script_argument)
65 | elif sys.argv[1] == "restore":
66 | rc_conf.write_bytes(rc_backup.read_bytes())
67 | sysctl_conf.write_bytes(sysctl_backup.read_bytes())
68 | loader_conf.write_bytes(loader_backup.read_bytes())
69 | print(f"\n*********************\033[38;5;76m Success \033[0;0m*************************")
70 | print("Original rc.conf, sysctl.conf, loader.conf restored")
71 | print(f"*******************************************************\n")
72 | exit(0)
73 | else:
74 | pass
75 | else:
76 | config.read('settings.ini')
77 |
78 |
79 | # Handle Errors
80 | def exception_handler(func):
81 | def intake(*args, **kwargs):
82 | try:
83 | func(*args, **kwargs)
84 | except PermissionError as e:
85 | print(f"\n******************\033[38;5;1m Permissions \033[0;0m************************\n")
86 | print(f"Insufficient permissions {e}")
87 | print(f"*******************************************************\n")
88 | except OSError as e:
89 | print(f"\n********************\033[38;5;1m Locked \033[0;0m**************************\n")
90 | print(f"Perhaps file is busy, locked, process blocked, or raced:\n")
91 | print(f"{e}")
92 | print(f"*******************************************************\n")
93 | return intake
94 |
95 |
96 |
97 | # Write to either "syslog" (/var/log/messages) or "script" (/var/log/harden-freebsd.log)
98 | @exception_handler
99 | def writeLog(log_type, content):
100 | harden_freebsd_logwriter = open(harden_freebsd_log, "a")
101 | syslog.openlog("LOG_INFO")
102 | if log_type == "script":
103 | harden_freebsd_logwriter.writelines(content + os.linesep)
104 | elif log_type == "syslog":
105 | syslog.syslog(1, content)
106 | else:
107 | print(f"*******************************************************\n")
108 | print(f"\033[38;5;63m LOG: \033[0;0m {content}")
109 | print(f"*******************************************************\n")
110 |
111 |
112 |
113 | # Make *.original backups of all files only once
114 | if config['SCRIPT']['first_run'] == "True":
115 | try:
116 | harden_freebsd_log.touch()
117 | cron_access.touch()
118 | at_access.touch()
119 | rc_backup.write_bytes(rc_conf.read_bytes())
120 | sysctl_backup.write_bytes(sysctl_conf.read_bytes())
121 | loader_backup.write_bytes(loader_conf.read_bytes())
122 | login_backup.write_bytes(login_conf.read_bytes())
123 | except FileNotFoundError as e:
124 | error_path = Path(e.filename)
125 | print(f"\n********************\033[38;5;1m File Not Found \033[0;0m*******************")
126 | print(f"Filename: {error_path.parts}")
127 | print("*******************************************************\n")
128 | except PermissionError as e:
129 | print(f"\n******************\033[38;5;1m Permissions \033[0;0m************************\n")
130 | print(f"Insufficient permissions {e}")
131 | print(f"*******************************************************\n")
132 | except OSError as e:
133 | print(f"\n********************\033[38;5;1m Locked \033[0;0m**************************\n")
134 | print(f"Perhaps file is busy, locked, process blocked, or raced:\n")
135 | print(f"{e}")
136 | print(f"*******************************************************\n")
137 | else:
138 | writeLog("syslog", "System file backups complete")
139 | with open('settings.ini', 'w') as configfile:
140 | config.set('SCRIPT', 'first_run', 'False')
141 | config.write(configfile)
142 | print(f"\n*********************\033[38;5;76m Success \033[0;0m*************************")
143 | print(f"\033[38;5;75mCreated: \033[0;0m")
144 | print(f" {cron_access.name}, {at_access.name} \n")
145 | print(f"\033[38;5;75mBackups Made: \033[0;0m")
146 | print(f" {rc_backup.name}, {sysctl_backup.name}")
147 | print(f" {login_backup.name}, {loader_backup.name} \n")
148 | print(f"*******************************************************\n")
149 |
150 |
151 |
152 | # Read the system file content
153 | try:
154 | rc_content = rc_conf.read_text(encoding="utf-8")
155 | sysctl_content = sysctl_conf.read_text(encoding="utf-8")
156 | login_content = login_conf.read_text(encoding="utf-8")
157 | loader_content = loader_conf.read_text(encoding="utf-8")
158 | except FileNotFoundError as e:
159 | error_path = Path(e.filename)
160 | writeLog("script", "Error finding file " + error_path)
161 | print(f"\n*******************\033[38;5;1m File Not Found \033[0;0m********************")
162 | print(f"Filename: {error_path.name}")
163 | print(f"Directories used: {error_path.parts}\n")
164 | print("*******************************************************\n")
165 | except PermissionError as e:
166 | print(f"\n******************\033[38;5;1m Permissions \033[0;0m************************\n")
167 | print(f"Permission to read/append {e}")
168 | print(f"{os.stat(rc_conf)}{os.linesep}")
169 | print(f"{os.stat(sysctl_conf)}{os.linesep}")
170 | print(f"{os.stat(loader_conf)}{os.linesep}")
171 | print(f"{os.stat(cron_access)}{os.linesep}")
172 | print(f"{os.stat(at_access)}{os.linesep}")
173 | print(f"{os.stat(login_conf)}{os.linesep}")
174 | print(f"*******************************************************\n")
175 | else:
176 | print(
177 | f"{os.linesep}*********************\033[38;5;75m Running \033[0;0m*************************{os.linesep}"
178 | f"Loaded system files for read/append\n"
179 | f"*******************************************************{os.linesep}"
180 | )
181 | finally:
182 | writeLog("syslog", "Hardening in progress")
183 | print(f"\n********************\033[38;5;75m Info Panel \033[0;0m***********************")
184 | print(f"Executing {__file__}")
185 | print(f"Executing {date_time}")
186 | print(f"*******************************************************\n")
187 |
188 |
189 | # Main working class dealing with rc.conf and sysctl.conf
190 | class Conf:
191 | def __init__(self, file, setting, flag):
192 | self.file = file
193 | self.setting = setting
194 | self.flag = flag
195 |
196 | # Changes the flag from whatever it is currently to flag in settings.ini
197 | def setConf(self):
198 | try:
199 | with open(self.file, 'r+', encoding="us-ascii") as file_content:
200 | lines = file_content.readlines()
201 | for i, line in enumerate(lines):
202 | if line.startswith(self.setting):
203 | lines[i] = self.setting + "=" + self.flag + os.linesep
204 | file_content.seek(0)
205 | for line in lines:
206 | file_content.write(line)
207 | file_content.truncate()
208 | writeLog("script", self.setting + " was set to " + self.flag)
209 | except OSError as e:
210 | print(f"\n********************\033[38;5;1m Locked \033[0;0m**************************\n")
211 | print(f"Perhaps file is busy, locked, process blocked, or raced:\n")
212 | print(f"{e}")
213 | print(f"*******************************************************\n")
214 | else:
215 | print(f"\033[38;5;208m {self.setting} \033[0;0m changed to\033[38;5;208m {self.flag}\033[0;0m in\033[38;5;75m {self.file}\033[0;0m ")
216 |
217 | # Appends at the end of a file a directive that was not present previously
218 | def addConf(self):
219 | try:
220 | with open(self.file, 'a') as file_content:
221 | file_content.write(self.setting + "=" + self.flag + os.linesep)
222 | writeLog("script", self.setting + "=" + self.flag + " added")
223 | except OSError as e:
224 | print(f"\n********************\033[38;5;1m Locked \033[0;0m**************************\n")
225 | print(f"Perhaps file is busy, locked, process blocked, or raced:\n")
226 | print(f"{e}")
227 | print(f"*******************************************************\n")
228 | else:
229 | print(f"\033[38;5;63m {self.setting} \033[0;0m added to \033[38;5;75m{self.file}\033[0;0m ")
230 |
231 | # Checks to see if the directive is already in the conf, returns True if present.
232 | def checkConf(self) -> bool:
233 | self.found = False
234 | try:
235 | with open(self.file, 'r') as file_content:
236 | lines = file_content.readlines()
237 | for i, line in enumerate(lines):
238 | if line.startswith(self.setting):
239 | self.found = True
240 | else:
241 | pass
242 | return self.found
243 | except OSError as e:
244 | print(f"\n********************\033[38;5;1m Locked \033[0;0m**************************\n")
245 | print(f"Perhaps file is busy, locked, process blocked, or raced:\n")
246 | print(f"{e}")
247 | print(f"*******************************************************\n")
248 |
249 | # Checks proper flag and equality syntax in rc.conf and sysctl.conf with first-boot 13.2 directives
250 | # May not work with advanced flags added later
251 | def verifyConf(self):
252 | global conf_directives
253 | conf_directives = []
254 | sysctl_conf_verify = re.compile(r'[^\"]') # No quotes
255 | loader_rc_conf_verify = re.compile(r'^[\"].+[$\"]') # Pair of quotes
256 | try:
257 | with open(self.file, 'r+') as file_content:
258 | lines = file_content.readlines()
259 | for i, line in enumerate(lines):
260 | partitioned_line = line.partition("=")
261 | if line.isspace():
262 | pass
263 | elif line.startswith("#"):
264 | pass
265 | elif partitioned_line[1] != "=":
266 | print(f"\n*******************************************************")
267 | print(f"Error at {lines[i]}: No equality operator. Restored original.")
268 | print(f"*******************************************************\n")
269 | writeLog("script", "No equality operator at line " + lines[i].rstrip() + " in " + self.file.name)
270 | self.restoreConf()
271 | sys.exit()
272 | elif self.file == rc_conf and re.match(loader_rc_conf_verify, partitioned_line[2]) == None:
273 | print(f"\n*******************************************************")
274 | print(f"Error: {self.flag} not allowed in {lines[i]} in {self.file}. Restored original.")
275 | print(f"*******************************************************\n")
276 | writeLog("script", "Quote matching error at line " + lines[i].rstrip())
277 | self.restoreConf()
278 | sys.exit()
279 | elif self.file == loader_conf and re.match(loader_rc_conf_verify, partitioned_line[2]) == None:
280 | print(f"\n*******************************************************")
281 | print(f"Error: {self.flag} not allowed in {lines[i]} in {self.file}. Restored original.")
282 | print(f"*******************************************************\n")
283 | writeLog("script", "Quote matching error at line " + lines[i].rstrip())
284 | self.restoreConf()
285 | sys.exit()
286 | elif self.file == sysctl_conf and re.match(sysctl_conf_verify, partitioned_line[2]) == None:
287 | print(f"\n*******************************************************")
288 | print(f"Error: {self.flag} not allowed in {lines[i].rstrip()} in {self.file}. Restored original.")
289 | print(f"*******************************************************\n")
290 | writeLog("script", "Quote in sysctl.conf at line " + lines[i])
291 | self.restoreConf()
292 | sys.exit()
293 | else:
294 | conf_directives.append(line.rstrip())
295 | except OSError as e:
296 | print(f"\n********************\033[38;5;1m Locked \033[0;0m**************************\n")
297 | print(f"Perhaps file is busy, locked, process blocked, or raced:\n")
298 | print(f"{e}")
299 | print(f"*******************************************************\n")
300 |
301 | # If syntax verification fails, restore *.originals to prevent boot failure
302 | # If in single user read-only mode use commands:
303 | # zfs set readonly=false zroot
304 | # zfs mount -a
305 | def restoreConf(self):
306 | try:
307 | if self.file == rc_conf:
308 | shutil.copy(rc_backup, rc_conf)
309 | elif self.file == sysctl_conf:
310 | shutil.copy(sysctl_backup, sysctl_conf)
311 | elif self.file == loader_conf:
312 | shutil.copy(loader_backup, loader_conf)
313 | except FileNotFoundError as e:
314 | error_path = Path(e.filename)
315 | print(f"\n*******************\033[38;5;1m File Not Found \033[0;0m********************")
316 | print(f"Filename: {error_path.name}")
317 | print(f"Directories used: {error_path.parts}\n")
318 | print("*******************************************************\n")
319 | else:
320 | print(f"\n*********************\033[38;5;76m Success \033[0;0m*************************")
321 | print(f"Files restored")
322 | print("*******************************************************\n")
323 |
324 |
325 |
326 | # Hardcoded sections as only t e contain flags we can dynamically set and re-set.
327 | # Loops through all directives and sets each
328 | class SetOpts:
329 | def __init__(self, section):
330 | self.section = section
331 | if self.section == "STARTUP":
332 | file = rc_conf
333 | elif self.section == "SYSTEM":
334 | file = sysctl_conf
335 | elif self.section == "KERNEL":
336 | file = loader_conf
337 | else:
338 | pass
339 |
340 | for opt in config[self.section]:
341 | value = config[self.section][opt]
342 | conf_runner = Conf(file, opt, value)
343 | setting_present = conf_runner.checkConf()
344 | if setting_present:
345 | conf_runner.setConf()
346 | conf_runner.verifyConf()
347 | else:
348 | conf_runner.addConf()
349 | conf_runner.verifyConf()
350 |
351 |
352 |
353 | # Run shell commands for named section. Will error if sent setting.ini sections that have no shell commands.
354 | def shellCommand(section):
355 | try:
356 | for opt in config[section]:
357 | value = config[section][opt]
358 | command_result = subprocess.run([value], shell=True, timeout=1.7)
359 | except subprocess.CalledProcessError as e:
360 | syslog.syslog(syslog.LOG_ERR, "Failure: Shell Command")
361 | print(f"\n*********************\033[38;5;1m Shell Error \033[0;0m*********************")
362 | print(f"Command {e.args[1]} failed")
363 | print(f"Terminated by {command_result.returncode}")
364 | print(f"{command_result.stderr}")
365 | print("*******************************************************\n")
366 | except OSError as e:
367 | print(f"\n********************\033[38;5;1m Locked \033[0;0m**************************\n")
368 | print(f"Perhaps file is busy, locked, process blocked, or raced:\n")
369 | print(f"{e}")
370 | print(f"*******************************************************\n")
371 | else:
372 | print(f"\n*********************\033[38;5;76m Success \033[0;0m*************************")
373 | print(f"\033[38;5;208mShell Error: {opt}\033[0;0m {command_result.stdout}")
374 | print(f"*******************************************************\n")
375 |
376 |
377 |
378 | # Set chmod for added convienence of the adminstrator with error handling and logging
379 | @exception_handler
380 | def setChmod(file, setting):
381 | os.fchmod(file, setting)
382 | writeLog("script", file + "was set to " + setting )
383 |
384 |
385 |
386 |
387 | # Main
388 | writeLog("script", date_time)
389 | SetOpts("STARTUP")
390 | SetOpts("SYSTEM")
391 | SetOpts("KERNEL")
392 | shellCommand("FILESEC")
393 | shellCommand("USERSEC")
394 |
395 |
396 | # Write succesfull completion to console and syslog
397 | writeLog("script", "************ SUCCESS ************")
398 | writeLog("script", "All files and directives validate")
399 | writeLog("script", "*********************************")
400 | writeLog("syslog", "SUCCESS: Hardening completed")
401 |
402 | print(f"\n*********************\033[38;5;76m Success \033[0;0m*************************")
403 | print("All files and directives validate")
404 | print("Package Security Report generated; pkg-audit-report")
405 | print(f"*******************************************************\n")
406 |
407 | # EOF
408 |
--------------------------------------------------------------------------------
/images/harden-freebsd-logo.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wravoc/harden-freebsd/beef6365d0a15a7315dcfd541302ca6152d26f9b/images/harden-freebsd-logo.jpg
--------------------------------------------------------------------------------
/images/quadhelionEngineeringIcon.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wravoc/harden-freebsd/beef6365d0a15a7315dcfd541302ca6152d26f9b/images/quadhelionEngineeringIcon.jpg
--------------------------------------------------------------------------------
/minimum.ini:
--------------------------------------------------------------------------------
1 | ##########################################
2 | # Settings file for harden-freebsd.py
3 | #
4 | # No section can be entirely commented out
5 | # No section can be completely empty
6 | # Harmless to re-run same settings
7 | #
8 | # Settings can be changed as many
9 | # times as needed; re-run script.
10 | #
11 | ##########################################
12 |
13 |
14 | [STARTUP]
15 | microcode_update_enable = "YES"
16 | syslogd_flags = "-ss"
17 | clear_tmp_enable = "YES"
18 | icmp_drop_redirect = "NO"
19 | inetd_enable = "NO"
20 | portmap_enable = "YES"
21 | update_motd = "NO"
22 | pf_enable="NO"
23 |
24 |
25 | [SYSTEM]
26 | kern.securelevel = -1
27 | security.bsd.see_other_uids = 0
28 | security.bsd.see_other_gids = 0
29 | security.bsd.see_jail_proc = 0
30 | security.bsd.unprivileged_read_msgbuf = 0
31 | kern.randompid = 107
32 | net.inet.tcp.always_keepalive = 1
33 | net.inet.tcp.blackhole = 0
34 | net.inet.udp.blackhole = 0
35 | net.inet.tcp.path_mtu_discovery = 1
36 | hw.mds_disable = 3
37 | hw.spec_store_bypass_disable = 1
38 | kern.elf64.allow_wx = 0
39 |
40 |
41 |
42 | [KERNEL]
43 | hw.ibrs_disable = "1"
44 |
45 |
46 | [FILESEC]
47 | lockout_other_group = chmod o= /etc/ftpusers /etc/group /etc/hosts /etc/hosts.allow /etc/hosts.equiv /etc/hosts.lpd /etc/inetd.conf /etc/login.access /etc/login.conf /etc/newsyslog.conf /etc/rc.conf /etc/ssh/sshd_config /etc/sysctl.conf /etc/syslog.conf /etc/ttys /etc/crontab /usr/bin/at /usr/bin/atq /usr/bin/atrm /usr/bin/batch /var/log
48 | lockdown_root = chmod 710 /root
49 |
50 |
51 | [USERSEC]
52 | set_cron_root_only = echo "root" | tee /var/cron/allow /var/at/at.allow > /dev/null
53 | enable_blowfish_passwords = sed -i .original 's/passwd_format=sha512/passwd_format=blf/g' /etc/login.conf
54 | enable_password_reset = sed -i .original 's/^default.*/& \n\t:passwordtime=120d:\\/' /etc/login.conf
55 | reset_login = cap_mkdb /etc/login.conf
56 | pkg_security_check = pkg audit -Fr > pkg-audit-report
57 |
58 | [SCRIPT]
59 | first_run = False
60 |
61 |
--------------------------------------------------------------------------------
/server.ini:
--------------------------------------------------------------------------------
1 | ##########################################
2 | # Settings file for harden-freebsd.py
3 | #
4 | # No section can be entirely commented out
5 | # No section can be completely empty
6 | # Harmless to re-run same settings
7 | #
8 | # Settings can be changed as many
9 | # times as needed; re-run script.
10 | #
11 | ##########################################
12 |
13 |
14 | [STARTUP]
15 | kern_securelevel_enable = "YES"
16 | microcode_update_enable = "YES"
17 | sendmail_enable = "NONE"
18 | sendmail_outbound_enable = "NO"
19 | sendmail_submit_enable = "NO"
20 | sendmail_msp_queue_enable = "NO"
21 | syslogd_flags = "-ss"
22 | clear_tmp_enable = "YES"
23 | icmp_drop_redirect = "YES"
24 | inetd_enable = "NO"
25 | portmap_enable = "NO"
26 | update_motd = "NO"
27 |
28 |
29 | [SYSTEM]
30 | kern.securelevel = 1
31 | security.bsd.see_other_uids = 0
32 | security.bsd.see_other_gids = 0
33 | security.bsd.see_jail_proc = 0
34 | security.bsd.unprivileged_read_msgbuf = 0
35 | kern.randompid = 107
36 | kern.ipc.maxsockbuf=67108864
37 | net.inet.tcp.sendbuf_max=67108864
38 | net.inet.tcp.recvbuf_max=67108864
39 | net.inet.tcp.sendbuf_auto=1
40 | net.inet.tcp.recvbuf_auto=1
41 | net.inet.tcp.sendbuf_inc=16384
42 | net.inet.tcp.cc.algorithm=htcp
43 | net.inet.ip.random_id = 1
44 | net.inet.ip.redirect = 0
45 | net.inet.tcp.always_keepalive = 0
46 | net.inet.tcp.blackhole = 2
47 | net.inet.udp.blackhole = 1
48 | net.inet.tcp.path_mtu_discovery = 0
49 | net.inet.icmp.drop_redirect = 1
50 | net.inet6.icmp6.rediraccept = 0
51 | net.inet.tcp.drop_synfin = 1
52 | hw.mds_disable = 3
53 | hw.spec_store_bypass_disable = 1
54 | kern.elf64.allow_wx = 0
55 |
56 |
57 |
58 | [KERNEL]
59 | security.bsd.allow_destructive_dtrace = "0"
60 | hw.ibrs_disable = "1"
61 |
62 |
63 | [FILESEC]
64 | lockout_other_group = chmod o= /etc/ftpusers /etc/group /etc/hosts /etc/hosts.allow /etc/hosts.equiv /etc/hosts.lpd /etc/inetd.conf /etc/login.access /etc/login.conf /etc/newsyslog.conf /etc/rc.conf /etc/ssh/sshd_config /etc/sysctl.conf /etc/syslog.conf /etc/ttys /etc/crontab /usr/bin/at /usr/bin/atq /usr/bin/atrm /usr/bin/batch /var/log
65 | lockdown_root = chmod 710 /root
66 |
67 |
68 | [USERSEC]
69 | set_cron_root_only = echo "root" | tee /var/cron/allow /var/at/at.allow > /dev/null
70 | enable_blowfish_passwords = sed -i .original 's/passwd_format=sha512/passwd_format=blf/g' /etc/login.conf
71 | enable_password_reset = sed -i .original 's/^default.*/& \n\t:passwordtime=120d:\\/' /etc/login.conf
72 | reset_login = cap_mkdb /etc/login.conf
73 | pkg_security_check = pkg audit -Fr > pkg-audit-report
74 |
75 | [SCRIPT]
76 | first_run = True
77 |
78 |
--------------------------------------------------------------------------------
/settings.ini:
--------------------------------------------------------------------------------
1 | ##########################################
2 | # Settings file for harden-freebsd.py
3 | #
4 | # No section can be entirely commented out
5 | # No section can be completely empty
6 | # Harmless to re-run same settings
7 | #
8 | # Settings can be changed as many
9 | # times as needed; re-run script.
10 | #
11 | ##########################################
12 |
13 |
14 | [STARTUP]
15 | kern_securelevel_enable = "YES"
16 | microcode_update_enable = "YES"
17 | sendmail_enable = "NONE"
18 | sendmail_outbound_enable = "NO"
19 | sendmail_submit_enable = "NO"
20 | sendmail_msp_queue_enable = "NO"
21 | syslogd_flags = "-ss"
22 | clear_tmp_enable = "YES"
23 | icmp_drop_redirect = "YES"
24 | inetd_enable = "NO"
25 | portmap_enable = "NO"
26 | update_motd = "NO"
27 | pf_enable="YES"
28 | pflog_enable="YES"
29 |
30 |
31 |
32 | [SYSTEM]
33 | kern.securelevel = 1
34 | security.bsd.see_other_uids = 0
35 | security.bsd.see_other_gids = 0
36 | security.bsd.see_jail_proc = 0
37 | security.bsd.unprivileged_read_msgbuf = 0
38 | kern.randompid = 107
39 | net.inet.ip.random_id = 1
40 | net.inet.ip.redirect = 0
41 | net.inet.tcp.always_keepalive = 0
42 | net.inet.tcp.blackhole = 2
43 | net.inet.udp.blackhole = 1
44 | net.inet.tcp.path_mtu_discovery = 0
45 | net.inet.icmp.drop_redirect = 1
46 | net.inet6.icmp6.rediraccept = 0
47 | net.inet.tcp.drop_synfin = 1
48 | hw.mds_disable = 3
49 | hw.spec_store_bypass_disable = 1
50 | kern.elf64.allow_wx = 0
51 |
52 |
53 |
54 | [KERNEL]
55 | security.bsd.allow_destructive_dtrace = "0"
56 | hw.ibrs_disable = "1"
57 |
58 |
59 | [FILESEC]
60 | lockout_other_group = chmod o= /etc/ftpusers /etc/group /etc/hosts /etc/hosts.allow /etc/hosts.equiv /etc/hosts.lpd /etc/inetd.conf /etc/login.access /etc/login.conf /etc/newsyslog.conf /etc/rc.conf /etc/ssh/sshd_config /etc/sysctl.conf /etc/syslog.conf /etc/ttys /etc/crontab /usr/bin/at /usr/bin/atq /usr/bin/atrm /usr/bin/batch /var/log
61 | lockdown_root = chmod 710 /root
62 |
63 |
64 | [USERSEC]
65 | set_cron_root_only = echo "root" | tee /var/cron/allow /var/at/at.allow > /dev/null
66 | enable_harden_umask = sed -i .original3 's/umask=022/umask=027/g' /etc/login.conf
67 | enable_blowfish_passwords = sed -i .original 's/passwd_format=sha512/passwd_format=blf/g' /etc/login.conf
68 | enable_password_reset = sed -i .original 's/^default.*/& \n\t:passwordtime=120d:\\/' /etc/login.conf
69 | reset_login = cap_mkdb /etc/login.conf
70 | pkg_security_check = pkg audit -Fr > pkg-audit-report
71 |
72 | [SCRIPT]
73 | first_run = True
74 |
75 |
--------------------------------------------------------------------------------
/util/mmap_protect.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | // Author: u/zabolekar
5 | // URL: https://www.reddit.com/r/BSD/comments/10isrl3/notes_about_mmap_mprotect_and_wx_on_different_bsd/
6 | // Customized by Quadhelion Engineering
7 | // Compile it with cc mmap_mprotect.c, run it with ./a.out
8 |
9 | int main()
10 | {
11 | void* p = mmap(NULL, 1, PROT_WRITE|PROT_EXEC, MAP_ANON|MAP_PRIVATE, -1, 0);
12 |
13 | if (p == MAP_FAILED)
14 | {
15 | perror("\n*********************\033[38;5;76m Success \033[0;0m*************************\n Permission denied for shared memory map write and execute\n*******************************************************\n");
16 | }
17 | else
18 | {
19 | puts("\033[38;5;1mVULNERABLE\033[0;0m: Writable and executable memory mapped successfully");
20 | munmap(p, 1);
21 | }
22 |
23 | p = mmap(NULL, 1, PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
24 | if (p == MAP_FAILED)
25 | {
26 | perror("Map writable memory");
27 | }
28 | else
29 | {
30 | puts("\n * Writable memory mapped successfully");
31 |
32 | if (mprotect(p, 1, PROT_EXEC))
33 | perror("Can't make writable memory executable");
34 | else
35 | puts(" * Preparing writable memory for execution");
36 |
37 | if (mprotect(p, 1, PROT_WRITE|PROT_EXEC))
38 | perror("\n*********************\033[38;5;76m Success \033[0;0m*************************\n Can't make shared memory writable and executable\n*******************************************************\n");
39 | else
40 | puts("\033[38;5;1mVULNERABLE\033[0;0m: Shared memory successfully made writable and executable");
41 |
42 | munmap(p, 1);
43 | }
44 | puts("\n");
45 | }
--------------------------------------------------------------------------------
/util/pf.conf:
--------------------------------------------------------------------------------
1 | \##########################################################################
2 | ## Modern configuration with multiple IPv4 + IPv6, Multicast Lockdown
3 | ## Multi-homed DNS lockdown, JS stack cache friendly, Redis Lockdown
4 | #
5 | ## FreeBSD 14.0, Dragonfly BSD 6.4 compatible
6 | #
7 | ## Unbound DNS with Quad9 DoT - Tertiary IPv6 ## UNCOMMENT for FreeBSD 14.1
8 | ## Localhost Redis DB
9 | #
10 | ## Elias Christopher Griffin
11 | ## https://www.quadhelion.engineering
12 | #
13 | ## LICENSE: CC BY-NC-SA 4.0
14 | ##
15 | ##########################################################################
16 |
17 | ##########################################################################
18 | ## Special thanks to https://forums.freebsd.org/members/mickey.4512/
19 | ##########################################################################
20 |
21 |
22 |
23 | ##########################################################################
24 | ## Macros
25 | ## CUSTOMIZE
26 | ##########################################################################
27 | ext_if = "vio0"
28 | ipv6 = "SET IP HERE"
29 | ssh_port = "1974"
30 | admin_ips = "{107.77.1.1 107.77.1.2}"
31 | admin_ip_range = "107.77.1.1. - 107.77.254.254"
32 |
33 | ##########################################################################
34 | ## NO CUSTOMIZE ##
35 | ##
36 | ## IPv6 link-local, MC
37 | ##########################################################################
38 |
39 | PFX_LNKLOC = "FE80::/10"
40 |
41 | # IPv6 Solicited Node Multicast Prefix.
42 | MC_SOLNOD = "FF02::1:FF00:0/104"
43 |
44 | # IPv6 All Nodes Link Local Multicast Address.
45 | MC_NODLNK = "FF02::1"
46 |
47 |
48 |
49 | ##########################################################################
50 | ## Basic policy
51 | ## IPv6 Link-Local, Multicast, bugs with no-df
52 | ## Big Tech Email servers using 1460 sized segments
53 | ##########################################################################
54 | scrub in all
55 |
56 |
57 |
58 | ##########################################################################
59 | ## Last rule wins, so start with blocking everything incoming
60 | ##########################################################################
61 | # block in log all
62 |
63 |
64 |
65 | ##########################################################################
66 | ## Keep loopback fast, skipping filter
67 | ##########################################################################
68 | set skip on lo
69 |
70 |
71 |
72 | ##########################################################################
73 | ## Allow all out from host itself
74 | ## Allow Time and DNS out, remove logs once tested working
75 | ##########################################################################
76 | pass out inet all keep state
77 | pass out log proto udp to port 123 keep state
78 |
79 |
80 | ## Allow Quad9 IPv6, DNS over TLS with ECS, stateful return
81 | # pass out log on $ext_if proto { udp tcp } from $ipv6 to { 2620:fe::11, 2620:fe::fe:11 } port 853 keep state
82 |
83 |
84 |
85 | ##########################################################################
86 | ## Allow IPv6 Multicast, BGP
87 | ## Ping, traceroute disallowed
88 | ##########################################################################
89 | pass inet6 proto ipv6-icmp all icmp6-type routeradv
90 | pass inet6 proto ipv6-icmp all icmp6-type routersol
91 | pass inet6 proto ipv6-icmp all icmp6-type neighbradv
92 | pass inet6 proto ipv6-icmp all icmp6-type neighbrsol
93 |
94 |
95 | # Allow NS from unspecified to solicited node multicast address (DAD)
96 | pass quick inet6 proto icmp6 from :: to $MC_SOLNOD icmp6-type neighbrsol no state
97 |
98 |
99 | # Allow IPv6 Router Discovery.
100 | pass in quick inet6 proto icmp6 from $PFX_LNKLOC to $MC_NODLNK icmp6-type routeradv no state
101 |
102 |
103 | # Allow IPv6 Neighbor Discovery (ND/NUD/DAD).
104 | pass in quick inet6 proto icmp6 from { $PFX_LNKLOC, ($ext_if:network) } to { ($ext_if), $MC_SOLNOD } icmp6-type neighbrsol no state
105 | pass in quick inet6 proto icmp6 from { $PFX_LNKLOC, ($ext_if:network) } to { ($ext_if), $MC_NODLNK } icmp6-type neighbradv no state
106 |
107 | # Allow SSH
108 | pass quick proto tcp from $admin_ips to port $ssh_port
109 |
110 | ##########################################################################
111 | ## Packet filtering
112 | ## Watch pf in realtime: $ tcpdump -n -e -ttt -i pflog0
113 | ## Correlate to rules: $ pfctl -vvsr
114 | ##########################################################################
115 | antispoof log quick for $ext_if
116 |
117 |
118 | ## Block anything coming form source we have no back routes for
119 | block drop in log from no-route to any
120 |
121 | # Block outside access to Redis
122 | block in log on ! lo0 proto tcp to port 6379
123 |
124 |
125 | ## Block packets whose ingress interface does not match the one
126 | ## the route back to their source address
127 | block drop in log from urpf-failed to any
128 |
129 |
130 | # By default, do not permit remote connections to X11
131 | block return in log on ! lo0 proto tcp to port 6000:6010
132 |
133 |
--------------------------------------------------------------------------------
/util/robots.txt:
--------------------------------------------------------------------------------
1 | location = /robots.txt {
2 | add_header Content-Type text/plain;
3 | return 200 "User-agent: GPTBot \nUser-agent: ChatGPT-User\nUser-agent: Google-Extended\nUser-agent: CCBot\nUser-agent: baiduspider\nUser-agent: AdsBot-Google\nUser-agent: Mediapartners-Google\nUser-agent: Google-Safety\nUser-agent: anthropic-ai \nDisallow: /\n";
4 | }
5 |
6 |
7 |
8 | # User-agent: GPTBot
9 | # User-agent: ChatGPT-User
10 | # User-agent: Google-Extended
11 | # User-agent: CCBot
12 | # User-agent: baiduspider
13 | # User-agent: AdsBot-Google
14 | # User-agent: Mediapartners-Google
15 | # User-agent: Google-Safety
16 | # User-agent: anthropic-ai
17 | # Disallow: /
18 |
--------------------------------------------------------------------------------