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