sanitizer.go (1722B)
1 // GoToSocial 2 // Copyright (C) GoToSocial Authors admin@gotosocial.org 3 // SPDX-License-Identifier: AGPL-3.0-or-later 4 // 5 // This program is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Affero General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // This program is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Affero General Public License for more details. 14 // 15 // You should have received a copy of the GNU Affero General Public License 16 // along with this program. If not, see <http://www.gnu.org/licenses/>. 17 18 package httpclient 19 20 import ( 21 "net/netip" 22 "syscall" 23 24 "github.com/superseriousbusiness/gotosocial/internal/netutil" 25 ) 26 27 type sanitizer struct { 28 allow []netip.Prefix 29 block []netip.Prefix 30 } 31 32 // Sanitize implements the required net.Dialer.Control function signature. 33 func (s *sanitizer) Sanitize(ntwrk, addr string, _ syscall.RawConn) error { 34 // Parse IP+port from addr 35 ipport, err := netip.ParseAddrPort(addr) 36 if err != nil { 37 return err 38 } 39 40 if !(ntwrk == "tcp4" || ntwrk == "tcp6") { 41 return ErrInvalidNetwork 42 } 43 44 // Seperate the IP 45 ip := ipport.Addr() 46 47 // Check if this is explicitly allowed 48 for i := 0; i < len(s.allow); i++ { 49 if s.allow[i].Contains(ip) { 50 return nil 51 } 52 } 53 54 // Now check if explicity blocked 55 for i := 0; i < len(s.block); i++ { 56 if s.block[i].Contains(ip) { 57 return ErrReservedAddr 58 } 59 } 60 61 // Validate this is a safe IP 62 if !netutil.ValidateIP(ip) { 63 return ErrReservedAddr 64 } 65 66 return nil 67 }