1# @ohos.net.vpnExtension (Enhanced VPN Management) 2 3This module implements virtual private network (VPN) management, such as starting and stopping a third-party VPN. Third-party VPNs refer to VPN services provided by third parties. They usually support more security and privacy functions and more comprehensive customization options. Currently, the VPN capabilities provided to third-party applications are primarily used for creating virtual NICs and configuring VPN routing information. The connection tunnel process and internal connection protocols need to be implemented by the applications themselves. 4 5> **NOTE** 6> The initial APIs of this module are supported since API version 11. Newly added APIs will be marked with a superscript to indicate their earliest API version. 7 8## Modules to Import 9 10```js 11import { vpnExtension } from '@kit.NetworkKit'; 12``` 13 14## LinkAddress<sup>11+</sup> 15type LinkAddress = connection.LinkAddress 16 17Defines the network link address information. 18 19**System capability**: SystemCapability.Communication.NetManager.Core 20 21| Type | Description | 22| ------ | ------------------------------------------------------------ | 23| [connection.LinkAddress](./js-apis-net-connection.md#linkaddress) | Network link address information.| 24 25## RouteInfo<sup>11+</sup> 26type RouteInfo = connection.RouteInfo 27 28Defines the network route information. 29 30**System capability**: SystemCapability.Communication.NetManager.Core 31 32| Type | Description | 33| ------ | ------------------------------------------------------------ | 34| [connection.RouteInfo](./js-apis-net-connection.md#routeinfo) | Network route information.| 35 36## VpnExtensionContext<sup>11+</sup> 37type VpnExtensionContext = _VpnExtensionContext 38 39Defines the VPN extension context. It allows access to serviceExtension-specific resources. 40 41**System capability**: SystemCapability.Ability.AbilityRuntime.Core. 42 43| Type | Description | 44| ------ | ------------------------------------------------------------ | 45| [_VpnExtensionContext](./js-apis-inner-application-VpnExtensionContext.md) | VPN extension context.| 46 47## vpnExtension.startVpnExtensionAbility 48 49startVpnExtensionAbility(want: Want): Promise\<void> 50 51Enables the VPN extension ability. This API uses a promise to return the result. 52 53**System capability**: SystemCapability.Ability.AbilityRuntime.Core. 54 55**Model restriction**: This API can be used only in the stage model. 56 57**Parameters** 58 59| Name| Type | Mandatory| Description | 60| ------ | ----------------------------------- | ---- | ------------------ | 61| want | [Want](../apis-ability-kit/js-apis-app-ability-want.md) | Yes | Want information.| 62 63**Return value** 64 65| Type | Description | 66| -------------- | ----------------------- | 67| Promise\<void> | Promise that returns no value.| 68 69**Error codes** 70 71For details about the error codes, see [Ability Error Codes](../apis-ability-kit/errorcode-ability.md) and [Universal Error Codes](../errorcode-universal.md). 72 73| ID| Error Message | 74| --------- | -------------------------------------- | 75| 401 | If the input parameter is not valid parameter.| 76| 16000001 | The specified ability does not exist. | 77| 16000002 | Incorrect ability type. | 78| 16000006 | Cross-user operations are not allowed. | 79| 16000008 | The crowdtesting application expires. | 80| 16000011 | The context does not exist. | 81| 16000050 | Internal error. | 82| 16200001 | The caller has been released. | 83 84**Example** 85Stage model: 86 87```ts 88import { common, Want } from '@kit.AbilityKit'; 89import { vpnExtension } from '@kit.NetworkKit'; 90 91let want: Want = { 92 deviceId: "", 93 bundleName: "com.example.myvpndemo", 94 abilityName: "MyVpnExtAbility", 95}; 96 97@Entry 98@Component 99struct Index { 100 @State message: string = 'Hello World' 101 102 build() { 103 Row() { 104 Column() { 105 Text(this.message) 106 .fontSize(50) 107 .fontWeight(FontWeight.Bold).onClick(() => { 108 console.info("btn click") }) 109 Button('Start Extension').onClick(() => { 110 vpnExtension.startVpnExtensionAbility(want); 111 }).width('70%').fontSize(45).margin(16) 112 }.width('100%') 113 }.height('100%') 114 } 115} 116``` 117 118## vpnExtension.stopVpnExtensionAbility 119 120stopVpnExtensionAbility(want: Want): Promise\<void> 121 122Stops the VPN extension ability. This API uses a promise to return the result. 123 124**System capability**: SystemCapability.Ability.AbilityRuntime.Core. 125 126**Model restriction**: This API can be used only in the stage model. 127 128**Parameters** 129 130| Name| Type | Mandatory| Description | 131| ------ | ----------------------------------- | ---- | ---------------- | 132| want | [Want](../apis-ability-kit/js-apis-app-ability-want.md) | Yes | Want information.| 133 134**Return value** 135 136| Type | Description | 137| -------------- | ----------------------- | 138| Promise\<void> | Promise that returns no value.| 139 140**Error codes** 141 142For details about the error codes, see [Ability Error Codes](../apis-ability-kit/errorcode-ability.md) and [Universal Error Codes](../errorcode-universal.md). 143 144| ID| Error Message | 145| --------- | -------------------------------------- | 146| 401 | If the input parameter is not valid parameter.| 147| 16000001 | The specified ability does not exist. | 148| 16000002 | Incorrect ability type. | 149| 16000006 | Cross-user operations are not allowed. | 150| 16000011 | The context does not exist. | 151| 16000050 | Internal error. | 152| 16200001 | The caller has been released. | 153 154**Example** 155Stage model: 156 157```ts 158import { common, Want } from '@kit.AbilityKit'; 159import { vpnExtension } from '@kit.NetworkKit'; 160 161let want: Want = { 162 deviceId: "", 163 bundleName: "com.example.myvpndemo", 164 abilityName: "MyVpnExtAbility", 165}; 166 167@Entry 168@Component 169struct Index { 170 @State message: string = 'Hello World' 171 172 build() { 173 Row() { 174 Column() { 175 Text(this.message) 176 .fontSize(50) 177 .fontWeight(FontWeight.Bold).onClick(() => { 178 console.info("btn click") }) 179 Button('Start Extension').onClick(() => { 180 vpnExtension.startVpnExtensionAbility(want); 181 }).width('70%').fontSize(45).margin(16) 182 Button('Stop Extension').onClick(() => { 183 console.info("btn end") 184 vpnExtension.stopVpnExtensionAbility(want); 185 }).width('70%').fontSize(45).margin(16) 186 187 }.width('100%') 188 }.height('100%') 189 } 190} 191``` 192 193## vpnExtension.createVpnConnection 194 195createVpnConnection(context: VpnExtensionContext): VpnConnection 196 197Creates a **VpnConnection** object. 198 199> **NOTE** 200> 201> Before calling **createVpnConnection**, call **startVpnExtensionAbility** to enable the VPN function. 202 203**System capability**: SystemCapability.Communication.NetManager.Vpn 204 205**Model restriction**: This API can be used only in the stage model. 206 207**Parameters** 208 209| Name | Type | Mandatory| Description | 210| ------- | ------------------------------------------------------------ | ---- | -------------- | 211| context | [VpnExtensionContext](js-apis-inner-application-VpnExtensionContext.md) | Yes | Specified context.| 212 213**Return value** 214 215| Type | Description | 216| :------------------------------ | :---------------------- | 217| [VpnConnection](#vpnconnection) | VPN connection object.| 218 219**Error codes** 220 221For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 222 223| ID| Error Message | 224| --------- | ---------------- | 225| 401 | Parameter error. | 226 227**Example** 228Stage model: 229 230```ts 231import { vpnExtension, VpnExtensionAbility } from '@kit.NetworkKit'; 232import { common, Want } from '@kit.AbilityKit'; 233 234let context: vpnExtension.VpnExtensionContext; 235export default class MyVpnExtAbility extends VpnExtensionAbility { 236 onCreate(want: Want) { 237 let vpnConnection : vpnExtension.VpnConnection = vpnExtension.createVpnConnection(context); 238 console.info("VPN createVpnConnection: " + JSON.stringify(vpnConnection)); 239 } 240} 241``` 242 243## VpnConnection 244 245Defines a VPN connection object. Before calling **VpnConnection** APIs, you need to create a VPN connection object by calling **vpnExt.createVpnConnection**. 246 247### create 248 249create(config: VpnConfig): Promise\<number\> 250 251Creates a VPN based on the specified configuration. This API uses a promise to return the result. 252 253**System capability**: SystemCapability.Communication.NetManager.Vpn 254 255**Parameters** 256 257| Name| Type | Mandatory| Description | 258| ------ | ----------------------- | ---- | ------------------------- | 259| config | [VpnConfig](#vpnconfig) | Yes | VPN configuration.| 260 261**Return value** 262 263| Type | Description | 264| ----------------- | -------------------------------------------------------------- | 265| Promise\<number\> | Promise used to return the result, which is the file descriptor of the virtual network interface card (vNIC).| 266 267**Error codes** 268 269For details about the error codes, see [VPN Error Codes](errorcode-net-vpn.md) and [Universal Error Codes](../errorcode-universal.md). 270 271| ID| Error Message | 272| --------- | ------------------------------------------------ | 273| 401 | Parameter error. | 274| 2200001 | Invalid parameter value. | 275| 2200002 | Operation failed. Cannot connect to service. | 276| 2200003 | System internal error. | 277| 2203001 | VPN creation denied, please check the user type. | 278| 2203002 | VPN exist already, please execute destroy first. | 279 280**Example** 281 282```js 283import { vpnExtension, VpnExtensionAbility } from '@kit.NetworkKit'; 284import { common, Want } from '@kit.AbilityKit'; 285import { hilog } from '@kit.PerformanceAnalysisKit'; 286 287let context: vpnExtension.VpnExtensionContext; 288export default class MyVpnExtAbility extends VpnExtensionAbility { 289 private tunIp: string = '10.0.0.5'; 290 private blockedAppName: string = 'com.example.myvpndemo'; 291 onCreate(want: Want) { 292 let vpnConnection : vpnExtension.VpnConnection = vpnExtension.createVpnConnection(context); 293 console.info("vpn createVpnConnection: " + JSON.stringify(vpnConnection)); 294 this.SetupVpn(); 295 } 296 SetupVpn() { 297 class Address { 298 address: string; 299 family: number; 300 301 constructor(address: string, family: number) { 302 this.address = address; 303 this.family = family; 304 } 305 } 306 307 class AddressWithPrefix { 308 address: Address; 309 prefixLength: number; 310 311 constructor(address: Address, prefixLength: number) { 312 this.address = address; 313 this.prefixLength = prefixLength; 314 } 315 } 316 317 class Config { 318 addresses: AddressWithPrefix[]; 319 mtu: number; 320 dnsAddresses: string[]; 321 trustedApplications: string[]; 322 blockedApplications: string[]; 323 324 constructor( 325 tunIp: string, 326 blockedAppName: string 327 ) { 328 this.addresses = [ 329 new AddressWithPrefix(new Address(tunIp, 1), 24) 330 ]; 331 this.mtu = 1400; 332 this.dnsAddresses = ["114.114.114.114"]; 333 this.trustedApplications = []; 334 this.blockedApplications = [blockedAppName]; 335 } 336 } 337 338 let config = new Config(this.tunIp, this.blockedAppName); 339 340 try { 341 let vpnConnection : vpnExtension.VpnConnection = vpnExtension.createVpnConnection(context); 342 vpnConnection.create(config).then((data) => { 343 hilog.error(0x0000, 'developTag', 'tunfd: %{public}s', JSON.stringify(data) ?? ''); 344 }) 345 } catch (error) { 346 hilog.error(0x0000, 'developTag', 'VPN setUp fail: %{public}s', JSON.stringify(error) ?? ''); 347 } 348 } 349} 350``` 351 352### protect 353 354protect(socketFd: number): Promise\<void\> 355 356Protects sockets against a VPN connection. The data sent through sockets is directly transmitted over the physical network and therefore the traffic does not traverse through the VPN. This API uses a promise to return the result. 357 358**System capability**: SystemCapability.Communication.NetManager.Vpn 359 360**Parameters** 361 362| Name | Type | Mandatory| Description | 363| -------- | ------ | ---- | ------------------------------------------------------------------------------------------- | 364| socketFd | number | Yes | Socket file descriptor. It can be obtained through [getSocketFd](js-apis-socket.md#getsocketfd10-1).| 365 366**Return value** 367 368| Type | Description | 369| --------------- | ----------------------------------------------------- | 370| Promise\<void\> | Promise that returns no value.| 371 372**Error codes** 373 374For details about the error codes, see [VPN Error Codes](errorcode-net-vpn.md) and [Universal Error Codes](../errorcode-universal.md). 375 376| ID| Error Message | 377| --------- | -------------------------------------------- | 378| 401 | Parameter error. | 379| 2200001 | Invalid parameter value. | 380| 2200002 | Operation failed. Cannot connect to service. | 381| 2200003 | System internal error. | 382| 2203004 | Invalid socket file descriptor. | 383 384**Example** 385 386```js 387import { vpnExtension, VpnExtensionAbility } from '@kit.NetworkKit'; 388import { common, Want } from '@kit.AbilityKit'; 389import { hilog } from '@kit.PerformanceAnalysisKit'; 390 391let g_tunnelFd = -1; 392let context: vpnExtension.VpnExtensionContext; 393export default class MyVpnExtAbility extends VpnExtensionAbility { 394 private vpnServerIp: string = '192.168.31.13'; 395 onCreate(want: Want) { 396 let vpnConnection : vpnExtension.VpnConnection = vpnExtension.createVpnConnection(context); 397 console.info("VPN createVpnConnection: " + JSON.stringify(vpnConnection)); 398 this.CreateTunnel(); 399 this.Protect(); 400 } 401 CreateTunnel() { 402 g_tunnelFd = 8888; 403 } 404 Protect() { 405 hilog.info(0x0000, 'developTag', '%{public}s', 'VPN Protect'); 406 let vpnConnection : vpnExtension.VpnConnection = vpnExtension.createVpnConnection(context); 407 vpnConnection.protect(g_tunnelFd).then(() => { 408 hilog.info(0x0000, 'developTag', '%{public}s', 'VPN Protect Success'); 409 }).catch((err : Error) => { 410 hilog.error(0x0000, 'developTag', 'VPN Protect Failed %{public}s', JSON.stringify(err) ?? ''); 411 }) 412 } 413} 414``` 415 416### destroy 417 418destroy(): Promise\<void\> 419 420Destroys a VPN. This API uses a promise to return the result. 421 422**System capability**: SystemCapability.Communication.NetManager.Vpn 423 424**Return value** 425 426| Type | Description | 427| --------------- | ----------------------------------------------------- | 428| Promise\<void\> | Promise that returns no value.| 429 430**Error codes** 431 432For details about the error codes, see [VPN Error Codes](errorcode-net-vpn.md) and [Universal Error Codes](../errorcode-universal.md). 433 434| ID| Error Message | 435| --------- | -------------------------------------------- | 436| 401 | Parameter error. | 437| 2200002 | Operation failed. Cannot connect to service. | 438| 2200003 | System internal error. | 439 440**Example** 441 442```js 443import { vpnExtension, VpnExtensionAbility } from '@kit.NetworkKit'; 444import { common, Want } from '@kit.AbilityKit'; 445import { BusinessError } from '@kit.BasicServicesKit'; 446 447let context: vpnExtension.VpnExtensionContext; 448export default class MyVpnExtAbility extends VpnExtensionAbility { 449 onCreate(want: Want) { 450 let vpnConnection : vpnExtension.VpnConnection = vpnExtension.createVpnConnection(context); 451 console.info("VPN createVpnConnection: " + JSON.stringify(vpnConnection)); 452 vpnConnection.destroy().then(() => { 453 console.info("destroy success."); 454 }).catch((error : BusinessError) => { 455 console.error("destroy fail" + JSON.stringify(error)); 456 }); 457 } 458} 459``` 460 461## VpnConfig 462 463Defines the VPN configuration. 464 465**System capability**: SystemCapability.Communication.NetManager.Vpn 466 467| Name | Type | Mandatory| Description | 468| ------------------- | -------------------------------------------------------------- | ---- |------------------------------------------------| 469| addresses | Array\<[LinkAddress](js-apis-net-connection.md#linkaddress)\> | Yes | IP addresses of vNICs. | 470| routes | Array\<[RouteInfo](js-apis-net-connection.md#routeinfo)\> | No | Routes of vNICs. Currently, a maximum of 1024 routes can be configured. | 471| dnsAddresses | Array\<string\> | No | IP address of the DNS server. | 472| searchDomains | Array\<string\> | No | List of DNS search domains. | 473| mtu | number | No | Maximum transmission unit (MTU), in bytes. The value range is [576,1500]. | 474| isIPv4Accepted | boolean | No | Whether IPv4 is supported. The value **true** indicates that the IPv4 is supported, and the value **false** indicates the opposite. The default value is **true**. | 475| isIPv6Accepted | boolean | No | Whether IPV6 is supported. The value **true** indicates that the IPV6 is supported, and the value **false** indicates the opposite. The default value is **false**.| 476| isInternal | boolean | No | Whether the built-in VPN is supported. The value **true** indicates that the built-in VPN is supported, and the value **false** indicates the opposite. The default value is **false**.| 477| isBlocking | boolean | No | Whether the blocking mode is used. The value **true** indicates that the blocking mode is used, and the value **false** indicates the opposite. The default value is **false**. | 478| trustedApplications | Array\<string\> | No | List of trusted applications, which are represented by package names of the string type. | 479| blockedApplications | Array\<string\> | No | List of blocked applications, which are represented by package names of the string type. | 480 481**Example** 482 483```js 484import { vpnExtension} from '@kit.NetworkKit'; 485 486let vpnConfig: vpnExtension.VpnConfig = { 487 addresses: [], 488 routes: [{ 489 interface: "eth0", 490 destination: { 491 address: { 492 address:'', 493 family:1, 494 port:8080 495 }, 496 prefixLength:1 497 }, 498 gateway: { 499 address:'', 500 family:1, 501 port:8080 502 }, 503 hasGateway: true, 504 isDefaultRoute: true, 505 }], 506 mtu: 1400, 507 dnsAddresses: ["223.5.5.5", "223.6.6.6"], 508 trustedApplications: [], 509 blockedApplications: [], 510} 511let context: vpnExtension.VpnExtensionContext; 512 513function vpnCreate(){ 514 let vpnConnection: vpnExtension.VpnConnection = vpnExtension.createVpnConnection(context); 515 vpnConnection.create(vpnConfig).then((data) => { 516 console.info("VPN create " + JSON.stringify(data)); 517 }) 518} 519``` 520