The short answer is yes, you can do it. The long answer is that it won't be a very good firewall. There are a few obstacles you will have to overcome.
- The Raspberry Pi only has one NIC.
- There is no "official" build of Ubuntu for the Raspberry Pi.
- Ubuntu is not natively designed to function as a firewall.
The first problem can be overcome a few ways. The easiest solution is to add a second NIC using a USB Ethernet adapter. This will put an increased power burden on your Pi so make sure you have a proper power adapter for it. Another issue you will run into is bandwidth. The USB pipeline on the Raspberry Pi is constrained. While it has one built-in NIC, that NIC is actually attached to the same bus as the USB ports, so your NICs will be competing with each other for access to the bus. Also, the Raspi does all of its NIC functions in software, so it isn't very fast. The most I have ever been able to push through a Raspberry Pi is 300Mbps, and that includes the new Raspberry Pi 4. You could help this out a little bit by using VLANs and building an 802.1q trunk to a switch, but now you are talking enterprise hardware and you could just buy a dedicated firewall.
The second problem is Ubuntu. There is no official build for the RasPi. You could run one of the unofficial builds, but I have found them to be slow and unreliable. That is a big deal for a security device. You could run Raspbian, which is an official port of Debian to the Raspi, but it wasn't designed with security in mind.
The last problem is native firewall functionality. Ubuntu was designed as a desktop first and a server second. Everything else falls by the wayside. That means if you configure pf or another firewall/router combination on it you will have to spend a good deal of time hardening the OS and removing unused features. That is why distros like pfSense and OpenWRT are so popular. They are designed as routers/firewalls from the beginning.
Personally, I use a Raspi as a personal server at home. It runs a web server, file server and email services alongside some tabletop gaming software and performs like a champ. My firewall, on the other hand, is running pfSense on a MiniITX board and handles my gigabit fiber connection without issues.
Hope that helps,