Comment configurer WireGuard VPN sur Debian 10

WireGuard est un VPN à usage général (réseau privé virtuel) qui utilise la cryptographie moderne. Comparé à d'autres solutions VPN populaires, telles que IPsec et OpenVPN, WireGuard est généralement plus rapide, plus facile à configurer et a un encombrement réduit. Il est multiplateforme et peut fonctionner presque n'importe où, y compris Linux, Windows, Android et macOS.

Wireguard est un VPN peer-to-peer ; il n'utilise pas le modèle client-serveur. Selon la configuration, un pair peut agir comme un serveur ou un client traditionnel. Il fonctionne en créant une interface réseau sur chaque pair qui agit comme un tunnel. Les pairs s'authentifient en échangeant et en validant des clés publiques, imitant le modèle SSH. La clé publique est mappée sur la liste des adresses IP autorisées dans le tunnel. Le trafic VPN est encapsulé en UDP.

Cet article explique comment installer et configurer WireGuard sur Debian 10 qui agira comme un serveur VPN. Nous vous montrerons également comment configurer WireGuard en tant que client sous Linux, Windows et macOS. Le trafic client sera acheminé via le serveur Debian 10.

Ce paramètre peut être utilisé comme défense contre les attaques de l'homme du milieu, surfer de manière anonyme, contourner le contenu géo-restreint ou permettre à vos collègues de travailler chez eux en toute sécurité, connectés au réseau de l'entreprise.

Conditions préalables

Pour suivre ce tutoriel, vous aurez besoin d'une machine avec Debian 10. Vous avez également besoin de root ou [accès sudo] ( https://linuxize.com/post/how-to-create-a-sudo-user-on-debian/   pour installer des packages et apporter des modifications au système.

Configuration du serveur WireGuard

Nous allons commencer par installer le paquet WireGuard sur une machine Debian et le configurer pour qu'il agisse en tant que serveur. Nous allons également configurer le système pour acheminer le trafic client à travers celui-ci.

Installation de WireGuard sur Debian 10

WireGuard est disponible dans le référentiel de rétroportages de Debian. Pour ajouter le référentiel à votre système, exécutez :

echo 'deb http://ftp.debian.org/debian buster-backports main' | sudo tee /etc/apt/sources.list.d/buster-backports.list

Après avoir activé le référentiel, mettez à jour le cache apt et installez le module et les outils WireGuard :

sudo apt update
sudo apt install wireguard

WireGuard fonctionne comme un module de noyau.

Configurer WireGuard

Vous pouvez configurer et gérer les interfaces WireGuard à l'aide d'outils de ligne de commande wget de wg-quick.

Chaque appareil du réseau VPN WireGuard doit avoir une clé privée et une clé publique. Exécutez la commande suivante pour générer la paire de clés :

wg genkey | sudo tee /etc/wireguard/privatekey | wg pubkey | sudo tee /etc/wireguard/publickey

Les fichiers sont créés dans /etc/wireguardle répertoire. Utilisez les commandes catou lesspour afficher le contenu des fichiers. La clé privée n'est jamais partagée avec qui que ce soit et doit toujours être conservée en lieu sûr.

Wireguard prend également en charge les clés pré-partagées, ajoutant une couche supplémentaire de cryptographie à clé symétrique. Cette clé est facultative et doit être unique pour chaque paire de pairs.

L'étape suivante consiste à configurer le périphérique de tunneling qui acheminera le trafic VPN.
 

L'appareil peut être configuré à partir de la ligne de commande avec des commandes ipet/ wgou en créant manuellement un fichier de configuration. Nous allons créer la configuration à l'aide d'un éditeur de texte.

Ouvrez votre éditeur et créez un nouveau fichier nommé wg0.confavec le contenu suivant :

sudo nano /etc/wireguard/wg0.conf

/etc/wireguard/wg0.conf

[Interface]
Address = 10.0.0.1/24
SaveConfig = true
ListenPort = 51820
PrivateKey = SERVER_PRIVATE_KEY
PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -t nat -A POSTROUTING -o ens3 -j MASQUERADE
PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -t nat -D POSTROUTING -o ens3 -j MASQUERADE

Vous pouvez nommer l'interface comme vous le souhaitez. Cependant, il est recommandé d'utiliser quelque chose comme wg0ou wgvpn0.

Les paramètres de la section interface ont les significations suivantes :

Adresses - Liste séparée par des virgules d'adresses IP v4 ou v6 pour les wg0interfaces. Vous pouvez vous attribuer une adresse IP à partir d'une plage réservée aux réseaux privés (10.0.0.0/8, 172.16.0.0/12 ou 192.168.0.0/16).

ListenPort - Port d'écoute.
 

PrivateKey - Une clé privée générée par la wg genkeycommande. (Pour voir le contenu du fichier tapez sudo cat /etc/wireguard/privatekey:)

SaveConfig - Lorsqu'il est défini sur true, l'état actuel de l'interface est enregistré dans le fichier de configuration à l'arrêt.

PostUp - Commande ou script à exécuter avant d'ouvrir l'interface. Dans cet exemple, nous utilisons iptables pour activer l'usurpation d'identité. Cela permet au trafic de quitter le serveur, ce qui permet aux clients VPN d'accéder à Internet.

Assurez-vous de remplacer ce qui ens3suit -A POSTROUTINGpour qu'il corresponde au nom de votre interface de réseau public. Vous pouvez facilement trouver l'interface avec :

ip -o -4 route show to default | awk '{print $5}'

PostDown - Une commande ou un script à exécuter avant de fermer l'interface. Les règles iptables seront supprimées une fois l'interface en panne.

Les fichiers wg0.confet les privatekeyfichiers ne peuvent pas être lus par les utilisateurs normaux . Utilisez chmodpour définir les autorisations de fichier sur600 :

sudo chmod 600 /etc/wireguard/{privatekey,wg0.conf}

Une fois cela fait, ouvrez wg0l'interface en utilisant les propriétés spécifiées dans le fichier de configuration :

sudo wg-quick up wg0

La sortie ressemblera à ceci :

[#] ip link add wg0 type wireguard
[#] wg setconf wg0 /dev/fd/63
[#] ip -4 address add 10.0.0.1/24 dev wg0
[#] ip link set mtu 1420 up dev wg0
[#] iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o ens3 -j MASQUERADE

Pour vérifier l'état et la configuration de l'interface, exécutez :
 

sudo wg show wg0
interface: wg0
  public key: +Vpyku+gjVJuXGR/OXXt6cmBKPdc06Qnm3hpRhMBtxs=
  private key: (hidden)
  listening port: 51820

Vous pouvez également vérifier l'état de l'interface avec ip a show wg0:

ip a show wg0
4: wg0: <POINTOPOINT,NOARP,UP,LOWER_UP> mtu 1420 qdisc noqueue state UNKNOWN group default qlen 1000
    link/none 
    inet 10.0.0.1/24 scope global wg0
       valid_lft forever preferred_lft forever

WireGuard peut être géré à l'aide de Systemd. Pour inclure l'interface WireGuard au démarrage, exécutez la commande suivante :

sudo systemctl enable wg-quick@wg0

Configurer le pare-feu et le réseau de serveurs

Le transfert IP doit être activé pour que NAT fonctionne. Ouvrez le /etc/sysctl.conffichier et ajoutez ou décommentez la ligne suivante :

sudo nano /etc/sysctl.conf

/etc/sysctl.conf

net.ipv4.ip_forward=1

Enregistrez le fichier et appliquez les modifications :

sudo sysctl -p
net.ipv4.ip_forward = 1

Si vous utilisez UFW pour gérer votre pare - feu , vous devez ouvrir le trafic UDP sur le port51820 :
 

sudo ufw allow 51820/udp

C'est ça. Le serveur homologue Debian agira comme un serveur établi.

Configuration des clients Linux et macOS

Les instructions d'installation pour toutes les plates-formes prises en charge sont disponibles sur https://wireguard.com/install/ . Sur les systèmes Linux, vous pouvez installer des packages à l'aide du gestionnaire de packages de distribution et sur macOS avec brew.

Une fois installé, suivez les étapes ci-dessous pour configurer le périphérique client.

Le processus de configuration des clients Linux et macOS est le même que pour le serveur. Tout d'abord, générez une clé publique et privée :

wg genkey | sudo tee /etc/wireguard/privatekey | wg pubkey | sudo tee /etc/wireguard/publickey

Créez le fichier wg0.confet ajoutez le contenu suivant :

sudo nano /etc/wireguard/wg0.conf

/etc/wireguard/wg0.conf

[Interface]
PrivateKey = CLIENT_PRIVATE_KEY
Address = 10.0.0.2/24


[Peer]
PublicKey = SERVER_PUBLIC_KEY
Endpoint = SERVER_IP_ADDRESS:51820
AllowedIPs = 0.0.0.0/0

Copie

Les paramètres de l'interface ont la même signification que la configuration du serveur :

  • Adresses - Liste séparée par des virgules d'adresses IP v4 ou v6 pour les wg0interfaces.
  • PrivateKey - Pour afficher le contenu du fichier sur le client, exécutez : sudo cat /etc/wireguard/privatekey

La section homologue contient les champs suivants :

  • PublicKey - Une clé publique de l'homologue auquel vous souhaitez vous connecter. (Contenu /etc/wireguard/publickeydu fichier du serveur).
  • Point de terminaison - L'adresse IP ou le nom d'hôte de l'homologue auquel vous souhaitez vous connecter, suivi de deux points puis du numéro de port sur lequel l'homologue distant écoute.
  • AllowedIPs - Une liste séparée par des virgules d'adresses IP v4 ou v6 à partir desquelles le trafic entrant pour l'homologue est autorisé et vers lequel le trafic sortant pour cet homologue est dirigé. Nous utilisons 0.0.0.0/0 car nous acheminons le trafic et souhaitons que le serveur pair envoie des paquets avec n'importe quelle IP source.

Si vous devez configurer des clients supplémentaires, répétez simplement les mêmes étapes en utilisant une adresse IP privée différente.

Configuration du client Windows

Téléchargez et installez le package Windows msi à partir du site Web de WireGuard .

Une fois installé, ouvrez l'application WireGuard et cliquez sur « Ajouter un tunnel » -> « Ajouter un tunnel vide… » comme indiqué dans l'image ci-dessous :

Une paire de clés publiques est automatiquement générée et affichée à l'écran.

Saisissez un nom pour le tunnel et modifiez la configuration comme suit :

[Interface]
PrivateKey = CLIENT_PRIVATE_KEY
Address = 10.0.0.2/24


[Peer]
PublicKey = SERVER_PUBLIC_KEY
Endpoint = SERVER_IP_ADDRESS:51820
AllowedIPs = 0.0.0.0/0

Dans la section interface, ajoutez une nouvelle ligne pour spécifier l'adresse de tunneling client.

Dans le pair, ajoutez les champs suivants :

  • PublicKey - La clé publique du serveur Debian ( /etc/wireguard/publickeyfichier).
  • Point de terminaison - L'adresse IP du serveur Debian, suivie de deux points et du port WireGuard (51820).
  • IP autorisées - 0.0.0.0/0

Une fois terminé, cliquez sur le bouton « Enregistrer ».

Ajouter un client pair au serveur

La dernière étape consiste à ajouter la clé publique et l'adresse IP du client au serveur. Pour ce faire, exécutez la commande suivante sur le serveur Debian :

sudo wg set wg0 peer CLIENT_PUBLIC_KEY allowed-ips 10.0.0.2

Assurez-vous de la modifier CLIENT_PUBLIC_KEYavec la clé publique que vous avez générée sur le client ( sudo cat /etc/wireguard/publickey) et ajustez l'adresse IP du client si elle est différente. Les utilisateurs Windows peuvent copier la clé publique à partir de l'application WireGuard.

Une fois cela fait, revenez au client et affichez l'interface du tunnel.

Client Linux et macOS

Exécutez la commande suivante pour afficher l'interface :

sudo wg-quick up wg0

Vous devriez maintenant être connecté au serveur Debian et le trafic de votre client devrait y être acheminé. Vous pouvez tester la connexion avec :

sudo wg
interface: wg0
  public key: gFeK6A16ncnT1FG6fJhOCMPMeY4hZa97cZCNWis7cSo=
  private key: (hidden)
  listening port: 53527
  fwmark: 0xca6c

peer: r3imyh3MCYggaZACmkx+CxlD6uAmICI8pe/PGq8+qCg=
  endpoint: XXX.XXX.XXX.XXX:51820
  allowed ips: 0.0.0.0/0
  latest handshake: 53 seconds ago
  transfer: 3.23 KiB received, 3.50 KiB sent

Vous pouvez également ouvrir votre navigateur, taper « quelle est mon adresse IP » et vous devriez voir l'adresse IP de votre serveur Debian.

Pour arrêter le tunneling, désactivez wg0l'interface :

sudo wg-quick down wg0

Clients Windows

Si vous avez déjà installé WireGuard sur Windows, cliquez sur le bouton « Activer ». Une fois les pairs connectés, l'état du tunnel passe à Actif :

Conclusion

Nous vous avons montré comment installer WireGuard sur Debian 10 et le configurer en tant que serveur VPN. Ce paramètre vous permet de surfer de manière anonyme en gardant vos données de trafic privées.

What is GEEK

Buddha Community

Hal  Sauer

Hal Sauer

1591467180

Set Up OpenConnect VPN Server (ocserv) on Debian 10 Buster with Let’s Encrypt

This tutorial is going to show you how to run your own VPN server by installing OpenConnect VPN server on Debian 10 Buster. OpenConnect VPN server, aka ocserv, is an open-source implementation of the Cisco AnyConnnect VPN protocol, which is widely-used in businesses and universities. AnyConnect is an SSL-based VPN protocol that allows individual users to connect to a remote network.

#debian #debian server #linux #openconnect vpn #self hosted #self-hosted vpn #vpn

Background Fetch for React Native Apps

react-native-background-fetch

Background Fetch is a very simple plugin which attempts to awaken an app in the background about every 15 minutes, providing a short period of background running-time. This plugin will execute your provided callbackFn whenever a background-fetch event occurs.

There is no way to increase the rate which a fetch-event occurs and this plugin sets the rate to the most frequent possible — you will never receive an event faster than 15 minutes. The operating-system will automatically throttle the rate the background-fetch events occur based upon usage patterns. Eg: if user hasn't turned on their phone for a long period of time, fetch events will occur less frequently or if an iOS user disables background refresh they may not happen at all.

:new: Background Fetch now provides a scheduleTask method for scheduling arbitrary "one-shot" or periodic tasks.

iOS

  • There is no way to increase the rate which a fetch-event occurs and this plugin sets the rate to the most frequent possible — you will never receive an event faster than 15 minutes. The operating-system will automatically throttle the rate the background-fetch events occur based upon usage patterns. Eg: if user hasn't turned on their phone for a long period of time, fetch events will occur less frequently.
  • scheduleTask seems only to fire when the device is plugged into power.
  • ⚠️ When your app is terminated, iOS no longer fires events — There is no such thing as stopOnTerminate: false for iOS.
  • iOS can take days before Apple's machine-learning algorithm settles in and begins regularly firing events. Do not sit staring at your logs waiting for an event to fire. If your simulated events work, that's all you need to know that everything is correctly configured.
  • If the user doesn't open your iOS app for long periods of time, iOS will stop firing events.

Android

Installing the plugin

⚠️ If you have a previous version of react-native-background-fetch < 2.7.0 installed into react-native >= 0.60, you should first unlink your previous version as react-native link is no longer required.

$ react-native unlink react-native-background-fetch

With yarn

$ yarn add react-native-background-fetch

With npm

$ npm install --save react-native-background-fetch

Setup Guides

iOS Setup

react-native >= 0.60

Android Setup

react-native >= 0.60

Example

ℹ️ This repo contains its own Example App. See /example

import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  FlatList,
  StatusBar,
} from 'react-native';

import {
  Header,
  Colors
} from 'react-native/Libraries/NewAppScreen';

import BackgroundFetch from "react-native-background-fetch";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      events: []
    };
  }

  componentDidMount() {
    // Initialize BackgroundFetch ONLY ONCE when component mounts.
    this.initBackgroundFetch();
  }

  async initBackgroundFetch() {
    // BackgroundFetch event handler.
    const onEvent = async (taskId) => {
      console.log('[BackgroundFetch] task: ', taskId);
      // Do your background work...
      await this.addEvent(taskId);
      // IMPORTANT:  You must signal to the OS that your task is complete.
      BackgroundFetch.finish(taskId);
    }

    // Timeout callback is executed when your Task has exceeded its allowed running-time.
    // You must stop what you're doing immediately BackgroundFetch.finish(taskId)
    const onTimeout = async (taskId) => {
      console.warn('[BackgroundFetch] TIMEOUT task: ', taskId);
      BackgroundFetch.finish(taskId);
    }

    // Initialize BackgroundFetch only once when component mounts.
    let status = await BackgroundFetch.configure({minimumFetchInterval: 15}, onEvent, onTimeout);

    console.log('[BackgroundFetch] configure status: ', status);
  }

  // Add a BackgroundFetch event to <FlatList>
  addEvent(taskId) {
    // Simulate a possibly long-running asynchronous task with a Promise.
    return new Promise((resolve, reject) => {
      this.setState(state => ({
        events: [...state.events, {
          taskId: taskId,
          timestamp: (new Date()).toString()
        }]
      }));
      resolve();
    });
  }

  render() {
    return (
      <>
        <StatusBar barStyle="dark-content" />
        <SafeAreaView>
          <ScrollView
            contentInsetAdjustmentBehavior="automatic"
            style={styles.scrollView}>
            <Header />

            <View style={styles.body}>
              <View style={styles.sectionContainer}>
                <Text style={styles.sectionTitle}>BackgroundFetch Demo</Text>
              </View>
            </View>
          </ScrollView>
          <View style={styles.sectionContainer}>
            <FlatList
              data={this.state.events}
              renderItem={({item}) => (<Text>[{item.taskId}]: {item.timestamp}</Text>)}
              keyExtractor={item => item.timestamp}
            />
          </View>
        </SafeAreaView>
      </>
    );
  }
}

const styles = StyleSheet.create({
  scrollView: {
    backgroundColor: Colors.lighter,
  },
  body: {
    backgroundColor: Colors.white,
  },
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
    color: Colors.black,
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
    color: Colors.dark,
  },
});

export default App;

Executing Custom Tasks

In addition to the default background-fetch task defined by BackgroundFetch.configure, you may also execute your own arbitrary "oneshot" or periodic tasks (iOS requires additional Setup Instructions). However, all events will be fired into the Callback provided to BackgroundFetch#configure:

⚠️ iOS:

  • scheduleTask on iOS seems only to run when the device is plugged into power.
  • scheduleTask on iOS are designed for low-priority tasks, such as purging cache files — they tend to be unreliable for mission-critical tasks. scheduleTask will never run as frequently as you want.
  • The default fetch event is much more reliable and fires far more often.
  • scheduleTask on iOS stop when the user terminates the app. There is no such thing as stopOnTerminate: false for iOS.
// Step 1:  Configure BackgroundFetch as usual.
let status = await BackgroundFetch.configure({
  minimumFetchInterval: 15
}, async (taskId) => {  // <-- Event callback
  // This is the fetch-event callback.
  console.log("[BackgroundFetch] taskId: ", taskId);

  // Use a switch statement to route task-handling.
  switch (taskId) {
    case 'com.foo.customtask':
      print("Received custom task");
      break;
    default:
      print("Default fetch task");
  }
  // Finish, providing received taskId.
  BackgroundFetch.finish(taskId);
}, async (taskId) => {  // <-- Task timeout callback
  // This task has exceeded its allowed running-time.
  // You must stop what you're doing and immediately .finish(taskId)
  BackgroundFetch.finish(taskId);
});

// Step 2:  Schedule a custom "oneshot" task "com.foo.customtask" to execute 5000ms from now.
BackgroundFetch.scheduleTask({
  taskId: "com.foo.customtask",
  forceAlarmManager: true,
  delay: 5000  // <-- milliseconds
});

API Documentation

Config

Common Options

@param {Integer} minimumFetchInterval [15]

The minimum interval in minutes to execute background fetch events. Defaults to 15 minutes. Note: Background-fetch events will never occur at a frequency higher than every 15 minutes. Apple uses a secret algorithm to adjust the frequency of fetch events, presumably based upon usage patterns of the app. Fetch events can occur less often than your configured minimumFetchInterval.

@param {Integer} delay (milliseconds)

ℹ️ Valid only for BackgroundFetch.scheduleTask. The minimum number of milliseconds in future that task should execute.

@param {Boolean} periodic [false]

ℹ️ Valid only for BackgroundFetch.scheduleTask. Defaults to false. Set true to execute the task repeatedly. When false, the task will execute just once.

Android Options

@config {Boolean} stopOnTerminate [true]

Set false to continue background-fetch events after user terminates the app. Default to true.

@config {Boolean} startOnBoot [false]

Set true to initiate background-fetch events when the device is rebooted. Defaults to false.

NOTE: startOnBoot requires stopOnTerminate: false.

@config {Boolean} forceAlarmManager [false]

By default, the plugin will use Android's JobScheduler when possible. The JobScheduler API prioritizes for battery-life, throttling task-execution based upon device usage and battery level.

Configuring forceAlarmManager: true will bypass JobScheduler to use Android's older AlarmManager API, resulting in more accurate task-execution at the cost of higher battery usage.

let status = await BackgroundFetch.configure({
  minimumFetchInterval: 15,
  forceAlarmManager: true
}, async (taskId) => {  // <-- Event callback
  console.log("[BackgroundFetch] taskId: ", taskId);
  BackgroundFetch.finish(taskId);
}, async (taskId) => {  // <-- Task timeout callback
  // This task has exceeded its allowed running-time.
  // You must stop what you're doing and immediately .finish(taskId)
  BackgroundFetch.finish(taskId);
});
.
.
.
// And with with #scheduleTask
BackgroundFetch.scheduleTask({
  taskId: 'com.foo.customtask',
  delay: 5000,       // milliseconds
  forceAlarmManager: true,
  periodic: false
});

@config {Boolean} enableHeadless [false]

Set true to enable React Native's Headless JS mechanism, for handling fetch events after app termination.

  • 📂 index.js (MUST BE IN index.js):
import BackgroundFetch from "react-native-background-fetch";

let MyHeadlessTask = async (event) => {
  // Get task id from event {}:
  let taskId = event.taskId;
  let isTimeout = event.timeout;  // <-- true when your background-time has expired.
  if (isTimeout) {
    // This task has exceeded its allowed running-time.
    // You must stop what you're doing immediately finish(taskId)
    console.log('[BackgroundFetch] Headless TIMEOUT:', taskId);
    BackgroundFetch.finish(taskId);
    return;
  }
  console.log('[BackgroundFetch HeadlessTask] start: ', taskId);

  // Perform an example HTTP request.
  // Important:  await asychronous tasks when using HeadlessJS.
  let response = await fetch('https://reactnative.dev/movies.json');
  let responseJson = await response.json();
  console.log('[BackgroundFetch HeadlessTask] response: ', responseJson);

  // Required:  Signal to native code that your task is complete.
  // If you don't do this, your app could be terminated and/or assigned
  // battery-blame for consuming too much time in background.
  BackgroundFetch.finish(taskId);
}

// Register your BackgroundFetch HeadlessTask
BackgroundFetch.registerHeadlessTask(MyHeadlessTask);

@config {integer} requiredNetworkType [BackgroundFetch.NETWORK_TYPE_NONE]

Set basic description of the kind of network your job requires.

If your job doesn't need a network connection, you don't need to use this option as the default value is BackgroundFetch.NETWORK_TYPE_NONE.

NetworkTypeDescription
BackgroundFetch.NETWORK_TYPE_NONEThis job doesn't care about network constraints, either any or none.
BackgroundFetch.NETWORK_TYPE_ANYThis job requires network connectivity.
BackgroundFetch.NETWORK_TYPE_CELLULARThis job requires network connectivity that is a cellular network.
BackgroundFetch.NETWORK_TYPE_UNMETEREDThis job requires network connectivity that is unmetered. Most WiFi networks are unmetered, as in "you can upload as much as you like".
BackgroundFetch.NETWORK_TYPE_NOT_ROAMINGThis job requires network connectivity that is not roaming (being outside the country of origin)

@config {Boolean} requiresBatteryNotLow [false]

Specify that to run this job, the device's battery level must not be low.

This defaults to false. If true, the job will only run when the battery level is not low, which is generally the point where the user is given a "low battery" warning.

@config {Boolean} requiresStorageNotLow [false]

Specify that to run this job, the device's available storage must not be low.

This defaults to false. If true, the job will only run when the device is not in a low storage state, which is generally the point where the user is given a "low storage" warning.

@config {Boolean} requiresCharging [false]

Specify that to run this job, the device must be charging (or be a non-battery-powered device connected to permanent power, such as Android TV devices). This defaults to false.

@config {Boolean} requiresDeviceIdle [false]

When set true, ensure that this job will not run if the device is in active use.

The default state is false: that is, the for the job to be runnable even when someone is interacting with the device.

This state is a loose definition provided by the system. In general, it means that the device is not currently being used interactively, and has not been in use for some time. As such, it is a good time to perform resource heavy jobs. Bear in mind that battery usage will still be attributed to your application, and shown to the user in battery stats.


Methods

Method NameArgumentsReturnsNotes
configure{FetchConfig}, callbackFn, timeoutFnPromise<BackgroundFetchStatus>Configures the plugin's callbackFn and timeoutFn. This callback will fire each time a background-fetch event occurs in addition to events from #scheduleTask. The timeoutFn will be called when the OS reports your task is nearing the end of its allowed background-time.
scheduleTask{TaskConfig}Promise<boolean>Executes a custom task. The task will be executed in the same Callback function provided to #configure.
statuscallbackFnPromise<BackgroundFetchStatus>Your callback will be executed with the current status (Integer) 0: Restricted, 1: Denied, 2: Available. These constants are defined as BackgroundFetch.STATUS_RESTRICTED, BackgroundFetch.STATUS_DENIED, BackgroundFetch.STATUS_AVAILABLE (NOTE: Android will always return STATUS_AVAILABLE)
finishString taskIdVoidYou MUST call this method in your callbackFn provided to #configure in order to signal to the OS that your task is complete. iOS provides only 30s of background-time for a fetch-event -- if you exceed this 30s, iOS will kill your app.
startnonePromise<BackgroundFetchStatus>Start the background-fetch API. Your callbackFn provided to #configure will be executed each time a background-fetch event occurs. NOTE the #configure method automatically calls #start. You do not have to call this method after you #configure the plugin
stop[taskId:String]Promise<boolean>Stop the background-fetch API and all #scheduleTask from firing events. Your callbackFn provided to #configure will no longer be executed. If you provide an optional taskId, only that #scheduleTask will be stopped.

Debugging

iOS

🆕 BGTaskScheduler API for iOS 13+

  • ⚠️ At the time of writing, the new task simulator does not yet work in Simulator; Only real devices.
  • See Apple docs Starting and Terminating Tasks During Development
  • After running your app in XCode, Click the [||] button to initiate a Breakpoint.
  • In the console (lldb), paste the following command (Note: use cursor up/down keys to cycle through previously run commands):
e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"com.transistorsoft.fetch"]
  • Click the [ > ] button to continue. The task will execute and the Callback function provided to BackgroundFetch.configure will receive the event.

Simulating task-timeout events

  • Only the new BGTaskScheduler api supports simulated task-timeout events. To simulate a task-timeout, your fetchCallback must not call BackgroundFetch.finish(taskId):
let status = await BackgroundFetch.configure({
  minimumFetchInterval: 15
}, async (taskId) => {  // <-- Event callback.
  // This is the task callback.
  console.log("[BackgroundFetch] taskId", taskId);
  //BackgroundFetch.finish(taskId); // <-- Disable .finish(taskId) when simulating an iOS task timeout
}, async (taskId) => {  // <-- Event timeout callback
  // This task has exceeded its allowed running-time.
  // You must stop what you're doing and immediately .finish(taskId)
  print("[BackgroundFetch] TIMEOUT taskId:", taskId);
  BackgroundFetch.finish(taskId);
});
  • Now simulate an iOS task timeout as follows, in the same manner as simulating an event above:
e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateExpirationForTaskWithIdentifier:@"com.transistorsoft.fetch"]

Old BackgroundFetch API

  • Simulate background fetch events in XCode using Debug->Simulate Background Fetch
  • iOS can take some hours or even days to start a consistently scheduling background-fetch events since iOS schedules fetch events based upon the user's patterns of activity. If Simulate Background Fetch works, your can be sure that everything is working fine. You just need to wait.

Android

  • Observe plugin logs in $ adb logcat:
$ adb logcat *:S ReactNative:V ReactNativeJS:V TSBackgroundFetch:V
  • Simulate a background-fetch event on a device (insert <your.application.id>) (only works for sdk 21+:
$ adb shell cmd jobscheduler run -f <your.application.id> 999
  • For devices with sdk <21, simulate a "Headless JS" event with (insert <your.application.id>)
$ adb shell am broadcast -a <your.application.id>.event.BACKGROUND_FETCH

Download Details:
Author: transistorsoft
Source Code: https://github.com/transistorsoft/react-native-background-fetch
License: MIT license

#react  #reactnative  #mobileapp  #javascript 

Set Up Your Own WireGuard VPN Server on Debian

This tutorial is going to show you how to set up your own WireGuard VPN server on Debian. WireGuard is made specifically for the Linux kernel. It runs inside the Linux kernel and allows you to create fast, modern, and secure VPN tunnel.

#debian #debian server #linux #self hosted #vpn #wireguard

How To Install PHP 8.0 on Debian 10 / Debian 9

PHP is an open-source programming language used for web development, created by Rasmus Lerdorf in 1994. It is an HTML-embedded scripting language for creating dynamic websites such as blogs, internet forums, e-commerce portals, etc.

In this post, we will see how to install PHP 8.0 on  Debian 10 /  Debian 9.

Add PHP Repository

SURY, a third-party repository that offers PHP 8.0/7.x for the Debian operating system. Update the repository cache.

sudo apt update

Install the below packages.

sudo apt install -y curl wget gnupg2 ca-certificates lsb-release apt-transport-https

#debian #post #debian 10 #debian 9 #php

Gordon  Taylor

Gordon Taylor

1675997460

Set Up WireGuard VPN on Debian 10

WireGuard is a general-purpose VPN (Virtual Private Network) that utilizes state-of-the-art cryptography. Compared to other popular VPN solutions, such as IPsec and OpenVPN , WireGuard is generally faster, easier to configure, and has a smaller footprint. It is cross-platform and can run almost anywhere, including Linux, Windows, Android, and macOS.

Wireguard is a peer-to-peer VPN; it does not use the client-server model. Depending on the configuration, a peer can act as a traditional server or client. It works by creating a network interface on each peer device that acts as a tunnel. Peers authenticate each other by exchanging and validating public keys, mimicking the SSH model. Public keys are mapped with a list of IP addresses that are allowed in the tunnel. The VPN traffic is encapsulated in UDP.

This article explains how to install and configure WireGuard on Debian 10 that will act as a VPN server. We’ll also show you how to configure WireGuard as a client on Linux, Windows, and macOS. The client’s traffic will be routed through the Debian 10 server.

This setup can be used as a protection against Man in the Middle attacks, surfing the web anonymously, bypassing Geo-restricted content, or allowing your colleagues who work from home to connect to the company network securely.

Prerequisites

To follow this guide, you’ll need a machine with Debian 10 installed. You also need root or [sudo access](https://linuxize.com/post/how-to-create-a-sudo-user-on-debian/ to install packages and make changes to the system.

Setting Up the WireGuard Server

We’ll start by installing the WireGuard package on the Debian machine and set it up to act as a server. We’ll also configure the system to route the clients’ traffic through it.

Install WireGuard on Debian 10

WireGuard is available from the Debian backports repositories. To add the repository to your system, run:

echo 'deb http://ftp.debian.org/debian buster-backports main' | sudo tee /etc/apt/sources.list.d/buster-backports.list

Once the repository is enabled, update the apt cache and install the WireGuard module and tools:

sudo apt update
sudo apt install wireguard
WireGuard runs as a kernel module.

WireGuard runs as a kernel module.

Configuring WireGuard

You can configure and manage the WireGuard interfaces with the wg and wg-quick command-line tools.

Each device in the WireGuard VPN network needs to have a private and public key. Run the following command to generate the key pair:

wg genkey | sudo tee /etc/wireguard/privatekey | wg pubkey | sudo tee /etc/wireguard/publickey

The files are generated in the /etc/wireguard directory. Use the cat or less commands to view the contents of the files. The private key should never be shared with anyone and should always be kept secure.

Wireguard also supports a pre-shared key, which adds an additional layer of symmetric-key cryptography. This key is optional and must be unique for each peer pair.

The next step is to configure the tunnel device that will route the VPN traffic.

The device can be set up either from the command line using the ip and wg commands, or by manually creating the configuration file. We’ll create the configuration with a text editor.

Open your editor and create a new file named wg0.conf with the following contents:

sudo nano /etc/wireguard/wg0.conf

/etc/wireguard/wg0.conf

[Interface]
Address = 10.0.0.1/24
SaveConfig = true
ListenPort = 51820
PrivateKey = SERVER_PRIVATE_KEY
PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -t nat -A POSTROUTING -o ens3 -j MASQUERADE
PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -t nat -D POSTROUTING -o ens3 -j MASQUERADE

You can name the interface anything you want to. However it is recommended to use something like wg0 or wgvpn0.

The settings in the interface section have the following meaning:

Address - A comma-separated list of v4 or v6 IP addresses for the wg0 interface. You can you an IP address from a range that is reserved for the private networks (10.0.0.0/8, 172.16.0.0/12 or 192.168.0.0/16).

ListenPort - The listening port.

PrivateKey - A private key generated by the wg genkey command. (To see the contents of the file type: sudo cat /etc/wireguard/privatekey)

SaveConfig - When set to true, the current state of the interface is saved to the configuration file when shutdown.

PostUp - Command or script that is executed before bringing the interface up. In this example, we’re using iptables to enable masquerading. This allows traffic to leave the server, giving the VPN clients access to the Internet.

Make sure to replace ens3 after -A POSTROUTING to match the name of your public network interface. You can easily find the interface with:

ip -o -4 route show to default | awk '{print $5}'

PostDown - A command or script which is executed before bringing the interface down. The iptables rules will be removed once the interface is down.

The wg0.conf and privatekey files should not be readable to normal users. Use chmod to set the files permissions to 600:

sudo chmod 600 /etc/wireguard/{privatekey,wg0.conf}

Once done, bring the wg0 interface up using the attributes specified in the configuration file:

sudo wg-quick up wg0

The output will look something like this:

[#] ip link add wg0 type wireguard
[#] wg setconf wg0 /dev/fd/63
[#] ip -4 address add 10.0.0.1/24 dev wg0
[#] ip link set mtu 1420 up dev wg0
[#] iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o ens3 -j MASQUERADE

To check the interface state and configuration, run:

sudo wg show wg0
interface: wg0
  public key: +Vpyku+gjVJuXGR/OXXt6cmBKPdc06Qnm3hpRhMBtxs=
  private key: (hidden)
  listening port: 51820

You can also verify the interface state with ip a show wg0:

ip a show wg0
4: wg0: <POINTOPOINT,NOARP,UP,LOWER_UP> mtu 1420 qdisc noqueue state UNKNOWN group default qlen 1000
    link/none 
    inet 10.0.0.1/24 scope global wg0
       valid_lft forever preferred_lft forever

WireGuard can be managed with Systemd. To bring the WireGuard interface at boot time, run the following command:

sudo systemctl enable wg-quick@wg0

Server Networking and Firewall Configuration

IP forwarding must be enabled for NAT to work. Open the /etc/sysctl.conf file and add or uncomment the following line:

sudo nano /etc/sysctl.conf

/etc/sysctl.conf

net.ipv4.ip_forward=1

Save the file and apply the change:

sudo sysctl -p
net.ipv4.ip_forward = 1

If you are using UFW to manage your firewall you need to open UDP traffic on port 51820:

sudo ufw allow 51820/udp

That’s it. The Debian peer that will act as a server has been set up.

Linux and macOS Clients Setup

The installation instructions for all supported platforms are available at https://wireguard.com/install/ . On Linux systems, you can install the package using the distribution package manager and on macOS with brew.

Once installed, follow the steps below to configure the client device.

The process for setting up a Linux and macOS client is pretty much the same as you did for the server. First, generate the public and private keys:

wg genkey | sudo tee /etc/wireguard/privatekey | wg pubkey | sudo tee /etc/wireguard/publickey

Create the file wg0.conf and add the following contents:

sudo nano /etc/wireguard/wg0.conf

/etc/wireguard/wg0.conf

[Interface]
PrivateKey = CLIENT_PRIVATE_KEY
Address = 10.0.0.2/24


[Peer]
PublicKey = SERVER_PUBLIC_KEY
Endpoint = SERVER_IP_ADDRESS:51820
AllowedIPs = 0.0.0.0/0

The settings in the interface section have the same meaning as when setting up the server:

  • Address - A comma-separated list of v4 or v6 IP addresses for the wg0 interface.
  • PrivateKey - To see the contents of the file on the client machine, run: sudo cat /etc/wireguard/privatekey

The peer section contains the following fields:

  • PublicKey - A public key of the peer you want to connect to. (The contents of the server’s /etc/wireguard/publickey file).
  • Endpoint - An IP or hostname of the peer you want to connect to, followed by a colon and then a port number on which the remote peer listens to.
  • AllowedIPs - A comma-separated list of v4 or v6 IP addresses from which incoming traffic for the peer is allowed and to which outgoing traffic for this peer is directed. We’re using 0.0.0.0/0 because we are routing the traffic and want the server peer to send packets with any source IP.

If you need to configure additional clients, just repeat the same steps using a different private IP address.

Windows Clients Setup

Download and install the Windows msi package from the WireGuard website .

Once installed, open the WireGuard application and click on “Add Tunnel” -> “Add empty tunnel…” as shown on the image below:

WireGuard Windows add Tunnel

A publickey pair is automatically created and displayed on the screen.

WireGuard Windows Tunnel

Enter a name for the tunnel and edit the configuration as follows:

[Interface]
PrivateKey = CLIENT_PRIVATE_KEY
Address = 10.0.0.2/24


[Peer]
PublicKey = SERVER_PUBLIC_KEY
Endpoint = SERVER_IP_ADDRESS:51820
AllowedIPs = 0.0.0.0/0

Copy

In the interface section, add a new line to define the client tunnel Address.

In the peer section, add the following fields:

  • PublicKey - The public key of the Debian server (/etc/wireguard/publickey file).
  • Endpoint - The IP address of the Debian server followed by a colon and WireGuard port (51820).
  • AllowedIPs - 0.0.0.0/0

Once done, click on the “Save” button.

Add the Client Peer to the Server

The last step is to add the client’s public key and IP address to the server. To do that, run the following command on the Debian server:

sudo wg set wg0 peer CLIENT_PUBLIC_KEY allowed-ips 10.0.0.2

Make sure to change the CLIENT_PUBLIC_KEY with the public key you generated on the client machine (sudo cat /etc/wireguard/publickey) and adjust the client IP address if it is different. Windows users can copy the public key from the WireGuard application.

Once done, go back to the client machine and bring up the tunneling interface.

Linux and macOS Clients

Run the following command the bring up the interface:

sudo wg-quick up wg0

Now you should be connected to the Debian server, and the traffic from your client machine should be routed through it. You can check the connection with:

sudo wg
interface: wg0
  public key: gFeK6A16ncnT1FG6fJhOCMPMeY4hZa97cZCNWis7cSo=
  private key: (hidden)
  listening port: 53527
  fwmark: 0xca6c

peer: r3imyh3MCYggaZACmkx+CxlD6uAmICI8pe/PGq8+qCg=
  endpoint: XXX.XXX.XXX.XXX:51820
  allowed ips: 0.0.0.0/0
  latest handshake: 53 seconds ago
  transfer: 3.23 KiB received, 3.50 KiB sent

You can also open your browser, type “what is my ip”, and you should see your Debian server IP address.

To stop the tunneling, bring down the wg0 interface:

sudo wg-quick down wg0

Windows Clients

If you installed WireGuard on Windows, click on the “Activate” button. Once the peers are connected, the tunnel status will change to Active:

Conclusion

We have shown you how to install WireGuard on Debian 10 and configure it as a VPN server. This setup allows you to surf the web anonymously by keeping your traffic data private.

If you are facing any problems, feel free to leave a comment.

Original article source at: https://linuxize.com/

#debian #wireguard