guix-epistemia

Personal Guix channel
Log | Files | Refs

vpn.scm (18151B)


      1 (define-module (epistemia services vpn)
      2   #:use-module (srfi srfi-1)
      3   #:use-module (gnu services)
      4   #:use-module (gnu services shepherd)
      5   #:use-module (guix gexp)
      6   #:use-module (guix records)
      7   #:use-module (gnu packages vpn)
      8   #:use-module (epistemia packages vpn)
      9   #:export (amneziawg-service-type
     10 	    amneziawg-configuration
     11 	    amneziawg-peer))
     12 
     13 ;;;
     14 ;;; AmneziaWG.
     15 ;;; Pretty much copied wholesale from gnu/services/vpn.scm's Wireguard
     16 ;;; service, with some Amnezia-specific additions.
     17 ;;;
     18 
     19 (define-record-type* <amneziawg-peer>
     20   amneziawg-peer make-amneziawg-peer
     21   amneziawg-peer?
     22   (name              amneziawg-peer-name)
     23   (endpoint          amneziawg-peer-endpoint
     24                      (default #f))		;string
     25   (public-key        amneziawg-peer-public-key)	;string
     26   (preshared-key     amneziawg-peer-preshared-key
     27                      (default #f))		 ;string
     28   (allowed-ips       amneziawg-peer-allowed-ips) ;list of strings
     29   (keep-alive        amneziawg-peer-keep-alive
     30                      (default #f)))    ;integer
     31 
     32 (define-record-type* <amneziawg-configuration>
     33   amneziawg-configuration make-amneziawg-configuration
     34   amneziawg-configuration?
     35   (amneziawg              amneziawg-configuration-amneziawg ;file-like
     36                           (default amneziawg-tools))
     37   (interface              amneziawg-configuration-interface ;string
     38                           (default "wg0"))
     39   (addresses              amneziawg-configuration-addresses ;string
     40                           (default '("10.0.0.1/32")))
     41   (port                   amneziawg-configuration-port ;integer
     42                           (default 51820))
     43   (private-key            amneziawg-configuration-private-key ;maybe-string
     44                           (default "/etc/amneziawg/private.key"))
     45   (bootstrap-private-key? amneziawg-configuration-bootstrap-private-key? ;boolean
     46                           (default #t))
     47   (peers                  amneziawg-configuration-peers ;list of <wiregard-peer>
     48                           (default '()))
     49   (dns                    amneziawg-configuration-dns ;list of strings
     50                           (default '()))
     51   (mtu                    amneziawg-configuration-mtu ;integer
     52                           (default #f))
     53   (monitor-ips?           amneziawg-configuration-monitor-ips? ;boolean
     54                           (default #f))
     55   (monitor-ips-interval   amneziawg-configuration-monitor-ips-interval
     56                           (default "*/5 * * * *"))       ;string | list
     57   (pre-up                 amneziawg-configuration-pre-up ;list of strings
     58                           (default '()))
     59   (post-up                amneziawg-configuration-post-up ;list of strings
     60                           (default '()))
     61   (pre-down               amneziawg-configuration-pre-down ;list of strings
     62                           (default '()))
     63   (post-down              amneziawg-configuration-post-down ;list of strings
     64                           (default '()))
     65   (shepherd-requirement   amneziawg-configuration-shepherd-requirement ; list of symbols
     66                           (default '()))
     67   (table                  amneziawg-configuration-table ;string
     68                           (default "auto"))
     69   (auto-start?            amneziawg-configuration-auto-start? ;boolean
     70                           (default #t))
     71   ;; amneziawg-specific additions
     72   (header-protection-key  amneziawg-configuration-header-protection-key ;maybe-string
     73 			  (default "/etc/amneziawg/header.key"))
     74 
     75   (h1                     amneziawg-configuration-h1 ;integer
     76 			  (default 1))
     77   (h2                     amneziawg-configuration-h2 ;integer
     78 			  (default 2))
     79   (h3                     amneziawg-configuration-h3 ;integer
     80 			  (default 3))
     81   (h4                     amneziawg-configuration-h4 ;integer
     82 			  (default 4))
     83 
     84   (s1                     amneziawg-configuration-s1 ;integer
     85 			  (default 20))
     86   (s2                     amneziawg-configuration-s2 ;integer
     87 			  (default 20))
     88   (s3                     amneziawg-configuration-s3 ;integer
     89 			  (default 20))
     90   (s4                     amneziawg-configuration-s4 ;integer
     91 			  (default 20))
     92 
     93   (content-padding-addition amneziawg-configuration-content-padding-addition ;string
     94 			    (default "16-64"))
     95 
     96   ;; Optional pre-handshake obfuscation.
     97   (jc                     amneziawg-configuration-jc ;maybe-integer
     98 			  (default #f))
     99   (jmin                   amneziawg-configuration-jmin ;maybe-integer
    100 			  (default #f))
    101   (jmax                   amneziawg-configuration-jmax ;maybe-integer
    102 			  (default #f))
    103 
    104   (i1                     amneziawg-configuration-i1 ;maybe-string
    105 			  (default #f))
    106   (i2                     amneziawg-configuration-i2 ;maybe-string
    107 			  (default #f))
    108   (i3                     amneziawg-configuration-i3 ;maybe-string
    109 			  (default #f))
    110   (i4                     amneziawg-configuration-i4 ;maybe-string
    111 			  (default #f))
    112   (i5                     amneziawg-configuration-i5 ;maybe-string
    113 			  (default #f)))
    114 
    115 (define (amneziawg-configuration-file config)
    116   (define (peer->config peer)
    117     (match-record peer <amneziawg-peer>
    118       (name public-key endpoint allowed-ips keep-alive)
    119       (let ((lines (list
    120                     (format #f "[Peer]   #~a" name)
    121                     (format #f "PublicKey = ~a" public-key)
    122                     (format #f "AllowedIPs = ~{~a~^, ~}" allowed-ips)
    123                     (format #f "~@[Endpoint = ~a~]" endpoint)
    124                     (format #f "~@[PersistentKeepalive = ~a~]" keep-alive))))
    125         (string-join (remove string-null? lines) "\n"))))
    126 
    127   (define (peers->preshared-keys peer keys)
    128     (let ((public-key (amneziawg-peer-public-key peer))
    129           (preshared-key (amneziawg-peer-preshared-key peer)))
    130       (if preshared-key
    131           (cons* public-key preshared-key keys)
    132           keys)))
    133 
    134   (match-record config <amneziawg-configuration>
    135     (amneziawg interface addresses port private-key peers dns mtu
    136                pre-up post-up pre-down post-down table
    137 	       header-protection-key
    138 	       h1 h2 h3 h4
    139 	       s1 s2 s3 s4
    140 	       content-padding-addition
    141 	       jc jmin jmax
    142 	       i1 i2 i3 i4 i5)
    143     (let* ((config-file (string-append interface ".conf"))
    144            (peer-keys (fold peers->preshared-keys (list) peers))
    145            (peers (map peer->config peers))
    146            (config
    147             (computed-file
    148              "amneziawg-config"
    149              #~(begin
    150                  (use-modules (ice-9 format)
    151                               (srfi srfi-1))
    152 
    153                  (define lines
    154                    (list
    155                     "[Interface]"
    156                     (if (null? '#$addresses)
    157                         ""
    158                         (format #f "Address = ~{~a~^, ~}"
    159                                 (list #$@addresses)))
    160                     (format #f "~@[Table = ~a~]" #$table)
    161                     (if (null? '#$pre-up)
    162                         ""
    163                         (format #f "~{PreUp = ~a~%~}" (list #$@pre-up)))
    164                     (if #$private-key
    165                         (format #f "PostUp = ~a set %i private-key ~a\
    166 ~{ peer ~a preshared-key ~a~}"
    167                                 #$(file-append amneziawg "/bin/awg")
    168                                 #$private-key (list #$@peer-keys))
    169                         "")
    170 		    (if #$header-protection-key
    171                         (format #f "PostUp = ~a set %i header-protection-key ~a"
    172                                 #$(file-append amneziawg "/bin/awg")
    173                                 #$header-protection-key)
    174                         "")
    175                     (if (null? '#$post-up)
    176                         ""
    177                         (format #f "~{PostUp = ~a~%~}" (list #$@post-up)))
    178                     (if (null? '#$pre-down)
    179                         ""
    180                         (format #f "~{PreDown = ~a~%~}" (list #$@pre-down)))
    181                     (if (null? '#$post-down)
    182                         ""
    183                         (format #f "~{PostDown = ~a~%~}" (list #$@post-down)))
    184                     (format #f "~@[ListenPort = ~a~]" #$port)
    185                     (if (null? '#$dns)
    186                         ""
    187                         (format #f "DNS = ~{~a~^, ~}" (list #$@dns)))
    188                     (if (not #$mtu)
    189                         ""
    190                         (format #f "MTU = ~a" #$mtu))
    191 
    192 		    ;; amnezia-specific
    193 		    (format #f "H1 = ~a" #$h1)
    194 		    (format #f "H2 = ~a" #$h2)
    195 		    (format #f "H3 = ~a" #$h3)
    196 		    (format #f "H4 = ~a" #$h4)
    197 		    
    198 		    (format #f "S1 = ~a" #$s1)
    199 		    (format #f "S2 = ~a" #$s2)
    200 		    (format #f "S3 = ~a" #$s3)
    201 		    (format #f "S4 = ~a" #$s4)
    202 
    203 		    (format #f "~@[ContentPaddingAddition = ~a~] "
    204 			    #$content-padding-addition)
    205 
    206 		    (format #f "~@[Jc = ~a~]" #$jc)
    207 		    (format #f "~@[Jmin = ~a~]" #$jmin)
    208 		    (format #f "~@[Jmax = ~a~]" #$jmax)
    209 
    210 		    (format #f "~@[I1 = ~a~]" #$i1)
    211 		    (format #f "~@[I2 = ~a~]" #$i2)
    212 		    (format #f "~@[I3 = ~a~]" #$i3)
    213 		    (format #f "~@[I4 = ~a~]" #$i4)
    214 		    (format #f "~@[I5 = ~a~]" #$i5)))
    215 
    216                  (mkdir #$output)
    217                  (chdir #$output)
    218                  (call-with-output-file #$config-file
    219                    (lambda (port)
    220                      (format port "~a~%~%~{~a~%~^~%~}"
    221                              (string-join (remove string-null? lines) "\n")
    222                              '#$peers)))))))
    223       (file-append config "/" config-file))))
    224 
    225 (define (amneziawg-activation config)
    226   (match-record config <amneziawg-configuration>
    227     (private-key bootstrap-private-key? amneziawg)
    228     #~(begin
    229         (use-modules (guix build utils)
    230                      (ice-9 popen)
    231                      (ice-9 rdelim))
    232         (when (and #$private-key
    233                    #$bootstrap-private-key?)
    234           (mkdir-p (dirname #$private-key))
    235           (unless (file-exists? #$private-key)
    236             (let* ((pipe
    237                     (open-input-pipe (string-append
    238                                       #$(file-append amneziawg "/bin/awg")
    239                                       " genkey")))
    240                    (key (read-line pipe)))
    241               (call-with-output-file #$private-key
    242                 (lambda (port)
    243                   (display key port)))
    244               (chmod #$private-key #o400)
    245               (close-pipe pipe)))))))
    246 
    247 ;;; XXX: Copied from (guix scripts pack), changing define to define*.
    248 (define-syntax-rule (define-with-source (variable args ...) body body* ...)
    249   "Bind VARIABLE to a procedure accepting ARGS defined as BODY, also setting
    250 its source property."
    251   (begin
    252     (define* (variable args ...)
    253       body body* ...)
    254     (eval-when (load eval)
    255       (set-procedure-property! variable 'source
    256                                '(define* (variable args ...) body body* ...)))))
    257 
    258 (define (amneziawg-service-name interface)
    259   "Return the Amneziawg service name (a symbol) configured to use INTERFACE."
    260   (symbol-append 'amneziawg- (string->symbol interface)))
    261 
    262 (define-with-source (strip-port/maybe endpoint #:key ipv6?)
    263   "Strip the colon and port, if present in ENDPOINT, a string."
    264   (if ipv6?
    265       (if (string-prefix? "[" endpoint)
    266           (first (string-split (string-drop endpoint 1) #\])) ;ipv6
    267           endpoint)
    268       (first (string-split endpoint #\:)))) ;ipv4
    269 
    270 (define* (ipv4-address? address)
    271   "Predicate to check whether ADDRESS is a valid IPv4 address."
    272   (let ((address (strip-port/maybe address)))
    273     (false-if-exception
    274      (->bool (getaddrinfo address #f AI_NUMERICHOST AF_INET)))))
    275 
    276 (define* (ipv6-address? address)
    277   "Predicate to check whether ADDRESS is a valid IPv6 address."
    278   (let ((address (strip-port/maybe address #:ipv6? #t)))
    279     (false-if-exception
    280      (->bool (getaddrinfo address #f AI_NUMERICHOST AF_INET6)))))
    281 
    282 (define (host-name? name)
    283   "Predicate to check whether NAME is a host name, i.e. not an IP address."
    284   (not (or (ipv6-address? name) (ipv4-address? name))))
    285 
    286 (define (endpoint-host-names peers)
    287   "Return an association list of endpoint host names keyed by their peer
    288 public key, if any."
    289   (reverse
    290    (fold (lambda (peer host-names)
    291            (let ((public-key (amneziawg-peer-public-key peer))
    292                  (endpoint (amneziawg-peer-endpoint peer)))
    293              (if (and endpoint (host-name? endpoint))
    294                  (cons (cons public-key endpoint) host-names)
    295                  host-names)))
    296          '()
    297          peers)))
    298 
    299 (define (amneziawg-monitoring-program config)
    300   (match-record config <amneziawg-configuration>
    301     (interface monitor-ips-interval peers)
    302     (let ((host-names (endpoint-host-names peers)))
    303       (when (null? host-names)
    304         (warning (G_ "'monitor-ips?' is #t but no host name to monitor~%")))
    305 
    306       ;; Loosely based on Amneziawg's own 'reresolve-dns.sh' shell script
    307       ;; (see: https://raw.githubusercontent.com/Amneziawg/amneziawg-tools/
    308       ;; master/contrib/reresolve-dns/reresolve-dns.sh).
    309       (program-file
    310        (format #f "amneziawg-~a-monitoring" interface)
    311        (with-imported-modules (source-module-closure
    312                                '((gnu services herd)
    313                                  (guix build utils)))
    314          #~(begin
    315              (use-modules (gnu services herd)
    316                           (guix build utils)
    317                           (ice-9 popen)
    318                           (ice-9 match)
    319                           (ice-9 textual-ports)
    320                           (srfi srfi-1)
    321                           (srfi srfi-26))
    322 
    323              (define (resolve-host name)
    324                "Return the IP address resolved from NAME."
    325                (let* ((ai (car (getaddrinfo name)))
    326                       (sa (addrinfo:addr ai)))
    327                  (inet-ntop (sockaddr:fam sa)
    328                             (sockaddr:addr sa))))
    329 
    330              (define awg #$(file-append amneziawg "/bin/awg"))
    331 
    332              #$(procedure-source strip-port/maybe)
    333 
    334              (define service-name
    335                '#$(amneziawg-service-name interface))
    336 
    337              (when (live-service-running
    338                     (current-service service-name))
    339                (let* ((pipe (open-pipe* OPEN_READ awg "show"
    340                                         #$interface "endpoints"))
    341                       (lines (string-split (get-string-all pipe)
    342                                            #\newline))
    343                       ;; IPS is an association list mapping
    344                       ;; public keys to IP addresses.
    345                       (ips (map (match-lambda
    346                                   ((public-key ip)
    347                                    (cons public-key
    348                                          (strip-port/maybe ip))))
    349                                 (map (cut string-split <> #\tab)
    350                                      (remove string-null?
    351                                              lines)))))
    352                  (close-pipe pipe)
    353                  (for-each
    354                   (match-lambda
    355                     ((key . host-name)
    356                      (let ((resolved-ip (resolve-host
    357                                          (strip-port/maybe
    358                                           host-name)))
    359                            (current-ip (assoc-ref ips key)))
    360                        (unless (string=? resolved-ip current-ip)
    361                          (format #t "resetting `~a' peer \
    362 endpoint to `~a' due to stale IP (`~a' instead of `~a')~%"
    363                                  key host-name
    364                                  current-ip resolved-ip)
    365                          (invoke awg "set" #$interface "peer" key
    366                                  "endpoint" host-name)))))
    367                   '#$host-names)))))))))
    368 
    369 (define (amneziawg-shepherd-services config)
    370   (match-record config <amneziawg-configuration>
    371     (amneziawg interface monitor-ips? monitor-ips-interval shepherd-requirement)
    372     (let ((awg-quick (file-append amneziawg "/bin/awg-quick"))
    373           (auto-start? (amneziawg-configuration-auto-start? config))
    374           (config-file (amneziawg-configuration-file config)))
    375       (define monitoring-service
    376         (and monitor-ips?
    377              (shepherd-service
    378               (provision (list (symbol-append
    379                                 (amneziawg-service-name interface)
    380                                 '-monitoring)))
    381               (requirement (list 'user-processes
    382                                  (amneziawg-service-name interface)))
    383               (modules '((shepherd service timer)))
    384               (start #~(make-timer-constructor
    385                         #$(if (string? monitor-ips-interval)
    386                               #~(cron-string->calendar-event
    387                                  #$monitor-ips-interval)
    388                               monitor-ips-interval)
    389                         (command '(#$(amneziawg-monitoring-program config)))
    390                         #:wait-for-termination? #t))
    391               (stop #~(make-timer-destructor))
    392               (documentation "Monitor the Amneziawg VPN tunnel.")
    393               (actions (list shepherd-trigger-action)))))
    394 
    395       (cons (shepherd-service
    396              (requirement `(networking user-processes ,@shepherd-requirement))
    397              (provision (list (amneziawg-service-name interface)))
    398              (start #~(lambda _
    399                         (invoke #$awg-quick "up" #$config-file)))
    400              (stop #~(lambda _
    401                        (invoke #$awg-quick "down" #$config-file)
    402                        #f))                       ;stopped!
    403              (actions (list (shepherd-configuration-action config-file)))
    404              (auto-start? auto-start?)
    405              (documentation "Run the AmneziaWG VPN tunnel"))
    406             (or (and=> monitoring-service list)
    407                 '())))))
    408 
    409 (define amneziawg-service-type
    410   (service-type
    411    (name 'amneziawg)
    412    (extensions
    413     (list (service-extension shepherd-root-service-type
    414                              amneziawg-shepherd-services)
    415           (service-extension activation-service-type
    416                              amneziawg-activation)
    417           (service-extension profile-service-type
    418                              (compose list
    419                                       amneziawg-configuration-amneziawg))))
    420    (description "Set up AmneziaWG @acronym{VPN, Virtual Private Network}
    421 tunnels.")))