Malware – securing a new machine with a compromised network

I have a machine on my network that has been repeatedly compromised, and I try to understand how that happens. After the device was last compromised, I replaced all parts of the computer except the SATA DVD drive and the SD card reader. I then reinstalled Ubuntu 18 on the computer, logged in to the computer, and updated the computer with a network that was at risk. I figured this was not a problem since the machine was already logged in, but shortly thereafter my machine was compromised again and I'm trying to understand how.

It could be one of several ways:

1) There was hardware malware on the DVD drive or SD card reader that infected the new hard drive, allowing access to the machine after it was connected to the network.

2) It was compromised by an OS vulnerability prior to updating the computer because the attacker already had access to the network at the time I connected the computer before I had a chance to secure it.

What are the options in both scenarios?