├── .github └── workflows │ └── publish.yaml ├── .gitignore ├── .vscode ├── launch.json └── tasks.json ├── LICENSE ├── README.md ├── UFiber.Configurator.sln └── src └── UFiber.Configurator ├── CRC32.cs ├── NVRAM.cs ├── Program.cs └── UFiber.Configurator.csproj /.github/workflows/publish.yaml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | 3 | on: 4 | push: 5 | tags: 6 | - "v*" # Push events to matching v*, i.e. v1.0, v20.15.10 7 | 8 | jobs: 9 | osx: 10 | runs-on: macos-latest 11 | steps: 12 | - uses: actions/checkout@v2 13 | - name: Setup .NET Core 14 | uses: actions/setup-dotnet@v1 15 | with: 16 | dotnet-version: 5.0.x 17 | - name: Build 18 | run: | 19 | dotnet publish -r osx-x64 -c Release -p:PublishReadyToRun=true -p:PublishSingleFile=true -p:PublishTrimmed=true --self-contained true -o build/macos-x64 src/UFiber.Configurator 20 | - name: Pack 21 | working-directory: build 22 | run: | 23 | tar -czvf UFiber.Configurator-MacOS.tar.gz macos-x64 24 | - uses: actions/upload-artifact@v2 25 | if: success() 26 | with: 27 | name: UFiber.Configurator-MacOS.tar.gz 28 | path: build/UFiber.Configurator-MacOS.tar.gz 29 | linux: 30 | runs-on: ubuntu-latest 31 | steps: 32 | - uses: actions/checkout@v1 33 | - name: Setup .NET Core 34 | uses: actions/setup-dotnet@v1 35 | with: 36 | dotnet-version: 5.0.x 37 | - name: Build 38 | run: | 39 | dotnet publish -r linux-x64 -c Release -p:PublishReadyToRun=true -p:PublishSingleFile=true -p:PublishTrimmed=true --self-contained true -o build/linux-x64 src/UFiber.Configurator 40 | - name: Pack 41 | working-directory: build 42 | run: | 43 | tar -czvf UFiber.Configurator-Linux.tar.gz linux-x64 44 | - uses: actions/upload-artifact@v2 45 | if: success() 46 | with: 47 | name: UFiber.Configurator-Linux.tar.gz 48 | path: build/UFiber.Configurator-Linux.tar.gz 49 | windows: 50 | runs-on: windows-latest 51 | steps: 52 | - uses: actions/checkout@v1 53 | - name: Setup .NET Core 54 | uses: actions/setup-dotnet@v1 55 | with: 56 | dotnet-version: 5.0.x 57 | - name: Build 58 | run: | 59 | dotnet publish -r win-x64 -c Release -p:PublishReadyToRun=true -p:PublishSingleFile=true -p:PublishTrimmed=true --self-contained true -o build/win-x64 src/UFiber.Configurator 60 | - name: Pack 61 | working-directory: build 62 | run: | 63 | tar -czvf UFiber.Configurator-Windows.zip win-x64 64 | - uses: actions/upload-artifact@v2 65 | if: success() 66 | with: 67 | name: UFiber.Configurator-Windows.zip 68 | path: build/UFiber.Configurator-Windows.zip 69 | release: 70 | runs-on: ubuntu-latest 71 | needs: [osx, linux, windows] 72 | steps: 73 | - uses: actions/checkout@v2 74 | - uses: actions/download-artifact@v2 75 | with: 76 | name: UFiber.Configurator-MacOS.tar.gz 77 | path: build 78 | - uses: actions/download-artifact@v2 79 | with: 80 | name: UFiber.Configurator-Linux.tar.gz 81 | path: build 82 | - uses: actions/download-artifact@v2 83 | with: 84 | name: UFiber.Configurator-Windows.zip 85 | path: build 86 | - name: Create Release 87 | id: create_release 88 | uses: actions/create-release@master 89 | env: 90 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 91 | with: 92 | tag_name: ${{ github.ref }} 93 | release_name: Release ${{ github.ref }} 94 | draft: false 95 | prerelease: false 96 | - name: Upload MacOS 97 | uses: actions/upload-release-asset@v1 98 | env: 99 | GITHUB_TOKEN: ${{ github.token }} 100 | with: 101 | upload_url: ${{ steps.create_release.outputs.upload_url }} 102 | asset_path: build/UFiber.Configurator-MacOS.tar.gz 103 | asset_name: UFiber.Configurator-MacOS.tar.gz 104 | asset_content_type: application/gzip 105 | - name: Upload Linux 106 | uses: actions/upload-release-asset@v1 107 | env: 108 | GITHUB_TOKEN: ${{ github.token }} 109 | with: 110 | upload_url: ${{ steps.create_release.outputs.upload_url }} 111 | asset_path: build/UFiber.Configurator-Linux.tar.gz 112 | asset_name: UFiber.Configurator-Linux.tar.gz 113 | asset_content_type: application/gzip 114 | - name: Upload Windows 115 | uses: actions/upload-release-asset@v1 116 | env: 117 | GITHUB_TOKEN: ${{ github.token }} 118 | with: 119 | upload_url: ${{ steps.create_release.outputs.upload_url }} 120 | asset_path: build/UFiber.Configurator-Windows.zip 121 | asset_name: UFiber.Configurator-Windows.zip 122 | asset_content_type: application/zip 123 | 124 | 125 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | 352 | dumps 353 | patched 354 | build -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "UFiber.Configurator", 6 | "type": "coreclr", 7 | "request": "launch", 8 | "preLaunchTask": "build", 9 | "program": "${workspaceFolder}/src/UFiber.Configurator/bin/Debug/net5.0/UFiber.Configurator.dll", 10 | "args": [ 11 | "--host", 12 | "192.168.200.2", 13 | "--dry-run", 14 | "--vendor", 15 | "HWTC", 16 | "--serial", 17 | "41-4C-43-4C-90-12-34-5a", 18 | "--slid", 19 | "12345" 20 | ], 21 | "cwd": "${workspaceFolder}/src/UFiber.Configurator", 22 | "console": "internalConsole", 23 | "stopAtEntry": false 24 | } 25 | ] 26 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/src/UFiber.Configurator/UFiber.Configurator.csproj", 11 | "/property:GenerateFullPaths=true", 12 | "/consoleloggerparameters:NoSummary" 13 | ], 14 | "problemMatcher": "$msCompile" 15 | }, 16 | { 17 | "label": "publish", 18 | "command": "dotnet", 19 | "type": "process", 20 | "args": [ 21 | "publish", 22 | "${workspaceFolder}/src/UFiber.Configurator/UFiber.Configurator.csproj", 23 | "/property:GenerateFullPaths=true", 24 | "/consoleloggerparameters:NoSummary" 25 | ], 26 | "problemMatcher": "$msCompile" 27 | }, 28 | { 29 | "label": "watch", 30 | "command": "dotnet", 31 | "type": "process", 32 | "args": [ 33 | "watch", 34 | "run", 35 | "${workspaceFolder}/src/UFiber.Configurator/UFiber.Configurator.csproj", 36 | "/property:GenerateFullPaths=true", 37 | "/consoleloggerparameters:NoSummary" 38 | ], 39 | "problemMatcher": "$msCompile" 40 | } 41 | ] 42 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Unifi Tools 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # UFiber.Configurator 2 | 3 | > **Disclaimer**: This **NOT** an official tool nor it was endorsed in any way by Ubiquiti. This is a community driven tool. Even though we will do our best to help the community there are no implicity or explicity warranties whatsoever. Use at your own risk. 4 | 5 | FTTx became a quite popular technology to deliver high speed connectivity specially at homes (FTTH) on which on a single fiber optics terminal you can provision and deliver internet access, IPTV and VoIP. 6 | 7 | [Ubiquiti](https://www.ui.com) has a line of fiber optics networking products that target usually ISPs. Among those products, some of them in particular are used on the customer premises as a CPE, which receives the fiber optics line and transform it on ethernet which is usually called GPON CPE or ONT. 8 | 9 | The Ubiquiti products that fall on this category are: [UFiber Loco (UF-Loco)](https://www.ui.com/ufiber/ufiber-loco/), [UFiber Nano G (UF-Nano-G)](https://www.ui.com/ufiber/ufiber-nano-g/), [UFiber Instant (UF-Instant)](https://store.ui.com/collections/operator-ufiber/products/uf-instant). 10 | 11 | Even thought Ubiquiti advertive UF-Loco and UF-Nano-G as to support third party OLT devices on your ISP, the most "clean" usage requires a full UFiber networking deployment on your ISP to be as much as "plug and play" as possible. The UF-Instant is even worse, where Ubiquiti says that it *only* works if you are connected to a fiber optics line which is provided by an UFiber OLT. 12 | 13 | On UF-Loco and UF-Nano-G, the 3rd party support allow you to select a profile and set a very limited number of options to make it work with them which not always is enough to make it work on ISPs that have custom or more complex fiber networks. 14 | 15 | This tool allow you to overcome those limitations by patching UF-Loco and UF-Nano-G file system to allow those customizations and make it work properly with most of the ISPs. 16 | 17 | ## Why are you doing that and not using the UFiber admin pages? 18 | 19 | After frustrating attempts to provide feedback and ask Ubiquiti for the ability to change some of those configuration using the embedded admin web pages natively, and seeing many users having the same problem, we decided to create this small tool to make it a simple one shot patch for the problem. 20 | 21 | Most of us use FTTH and usually the clunky ISP ONT/Modems are pretty bad or provide a lot of limitations then we usually replace this modem with an custom GPON ONT device (like the ones mentioned here) and use our own routers to provide networking for our environments. 22 | 23 | ## How does it work? 24 | 25 | Essentially this is the flow: 26 | 1. Connects to your UFiber device using SSH and SCP; 27 | 2. Generate a dump of one of its partitions; 28 | 3. Pull the dump file to your host computer; 29 | 4. Apply the patch with the settings you passed to the tool as parameters (i.e. SLID, Vendor Id, Serial Number, MAC); 30 | 5. Push the file to the UFiber device; 31 | 6. Write the patched file to the original partition from which the dump was taken at first place. 32 | 33 | ## Supported UFiber devices 34 | 35 | - UF-Loco (firmware 4.3.1) 36 | - UF-Nano-G (firmware 4.3.1) 37 | - UF-Instant *(still under test)* 38 | 39 | ## Requirements 40 | 41 | Unlike other approaches found over the internet, this tool doesn't require any dependencies and is totally self-contained. 42 | 43 | All you need is: 44 | 45 | 1. A Windows, Linux or MacOS computer; 46 | 2. The target UFiber device with a supported firmware (you can download the firmware files from [Ubiquiti downloads page](https://www.ui.com/download/#!ufiber)); 47 | 3. Have SSH enabled on the target UFiber device. 48 | 4. Download the package from the [Releases section](https://github.com/Unifi-Tools/UFiber.Configurator/releases) of this repository for your OS. 49 | 50 | ## Usage 51 | 52 | By running the `UFiber.Configurator --help` you will get all the parameters used by this tool: 53 | 54 | ``` 55 | UFiber.Configurator 56 | Apply configuration changes to UFiber devices 57 | 58 | Usage: 59 | UFiber.Configurator [options] 60 | 61 | Options: 62 | --host IP or hostname of the target UFiber device. [default: 192.168.1.1] 63 | --user SSH user name. [default: ubnt] 64 | --pw SSH password. [default: ubnt] 65 | --port SSH port of the target UFiber device. [default: 22] 66 | --dry-run Don't apply the patched file to the target UFiber device. (i.e. dry-run) 67 | --slid The SLID (or PLOAM Password). 68 | --vendor 4-digit Vendor Id (e.g. HWTC, MTSC, etc.). Combined with --serial, a GPON Serial Number is 69 | built. 70 | --serial 8-digit (e.g. 01234567) serial number or 16-digit (e.g. 41-4C-43-4C-xx-xx-xx-xx) HEX serial 71 | number. Combined with --vendor, a GPON Serial Number is built. Note: If a 16-digit HEX 72 | value is provided, the first 4 bytes (8 digits) will replace whatever value was passed to 73 | Vendor Id with '--vendor'. 74 | --mac The desired MAC address to clone. 75 | --version Show version information 76 | -?, -h, --help Show help and usage information 77 | ``` 78 | 79 | ## Contributions and feedback 80 | 81 | Please feel free to open issues and contribute back. 82 | 83 | A huge thanks and kudos to [@jakesays](https://github.com/jakesays) for all the help while creating this tool. 84 | -------------------------------------------------------------------------------- /UFiber.Configurator.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.6.30114.105 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{7D598BFE-5D3E-4E92-BEAC-492BBFD00B02}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UFiber.Configurator", "src\UFiber.Configurator\UFiber.Configurator.csproj", "{3D31C840-16B1-4F68-A886-4B8E49246B81}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Debug|x64 = Debug|x64 14 | Debug|x86 = Debug|x86 15 | Release|Any CPU = Release|Any CPU 16 | Release|x64 = Release|x64 17 | Release|x86 = Release|x86 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 23 | {3D31C840-16B1-4F68-A886-4B8E49246B81}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 24 | {3D31C840-16B1-4F68-A886-4B8E49246B81}.Debug|Any CPU.Build.0 = Debug|Any CPU 25 | {3D31C840-16B1-4F68-A886-4B8E49246B81}.Debug|x64.ActiveCfg = Debug|Any CPU 26 | {3D31C840-16B1-4F68-A886-4B8E49246B81}.Debug|x64.Build.0 = Debug|Any CPU 27 | {3D31C840-16B1-4F68-A886-4B8E49246B81}.Debug|x86.ActiveCfg = Debug|Any CPU 28 | {3D31C840-16B1-4F68-A886-4B8E49246B81}.Debug|x86.Build.0 = Debug|Any CPU 29 | {3D31C840-16B1-4F68-A886-4B8E49246B81}.Release|Any CPU.ActiveCfg = Release|Any CPU 30 | {3D31C840-16B1-4F68-A886-4B8E49246B81}.Release|Any CPU.Build.0 = Release|Any CPU 31 | {3D31C840-16B1-4F68-A886-4B8E49246B81}.Release|x64.ActiveCfg = Release|Any CPU 32 | {3D31C840-16B1-4F68-A886-4B8E49246B81}.Release|x64.Build.0 = Release|Any CPU 33 | {3D31C840-16B1-4F68-A886-4B8E49246B81}.Release|x86.ActiveCfg = Release|Any CPU 34 | {3D31C840-16B1-4F68-A886-4B8E49246B81}.Release|x86.Build.0 = Release|Any CPU 35 | EndGlobalSection 36 | GlobalSection(NestedProjects) = preSolution 37 | {3D31C840-16B1-4F68-A886-4B8E49246B81} = {7D598BFE-5D3E-4E92-BEAC-492BBFD00B02} 38 | EndGlobalSection 39 | EndGlobal 40 | -------------------------------------------------------------------------------- /src/UFiber.Configurator/CRC32.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace UFiber.Configurator 4 | { 5 | internal static class CRC32 6 | { 7 | public static uint GenerateCrc(ReadOnlySpan data) 8 | { 9 | var crc = 0xFFFFFFFF; 10 | 11 | foreach (var bit in data) 12 | { 13 | crc = (crc >> 8) ^ _crcTable[(crc ^ bit) & 0xFF]; 14 | } 15 | 16 | return crc & 0xFFFFFFFF; 17 | } 18 | 19 | private static readonly uint[] _crcTable = 20 | { 21 | 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 22 | 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 23 | 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 24 | 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 25 | 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 26 | 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 27 | 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 28 | 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 29 | 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 30 | 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 31 | 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 32 | 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 33 | 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 34 | 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 35 | 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 36 | 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 37 | 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 38 | 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 39 | 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 40 | 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 41 | 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 42 | 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 43 | 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 44 | 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 45 | 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 46 | 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 47 | 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 48 | 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 49 | 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 50 | 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 51 | 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 52 | 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 53 | 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 54 | 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 55 | 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 56 | 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 57 | 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 58 | 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 59 | 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 60 | 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 61 | 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 62 | 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 63 | 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 64 | 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 65 | 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 66 | 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 67 | 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 68 | 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 69 | 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 70 | 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 71 | 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 72 | 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 73 | 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 74 | 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 75 | 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 76 | 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 77 | 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 78 | 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 79 | 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 80 | 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 81 | 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 82 | 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 83 | 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 84 | 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D 85 | }; 86 | } 87 | } -------------------------------------------------------------------------------- /src/UFiber.Configurator/NVRAM.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Security.Cryptography; 3 | using System.Text; 4 | using System.Text.RegularExpressions; 5 | using static System.BitConverter; 6 | 7 | namespace UFiber.Configurator 8 | { 9 | public class NVRAM 10 | { 11 | private const int NvRamCrcOffset = 0x3FC; 12 | private const int NvRamCrcLength = 4; 13 | private const uint NvRamOffset = 0x580; 14 | private const uint NvRamLength = 0x400; 15 | private static readonly Regex _snMatcher = new Regex(@"^(([a-fA-F0-9]){2}-){7}([a-fA-F0-9]){2}$"); 16 | private static readonly Regex _pwMatcher = new Regex(@"^(([a-fA-F0-9]){2}-){9}([a-fA-F0-9]){2}$"); 17 | public uint Checksum { get; private set; } 18 | public byte[] AfeId { get; } 19 | public byte[] VoiceBoardId { get; } 20 | public uint NandPartSizeKb { get; } 21 | public uint NandPartOfsKb { get; } 22 | public uint SyslogSize { get; } 23 | public byte[] WLanParams { get; } 24 | public byte[] WpsDevPin { get; } 25 | public string GponPassword { get; private set; } 26 | public byte[] GponVendorId { get; private set; } 27 | public byte[] GponVendorSerialNumber { get; private set; } 28 | public uint OldCheckSum { get; } 29 | public byte[] BaseMacAddr { get; private set; } 30 | public uint Version { get; } 31 | public uint NumMacAddr { get; } 32 | public uint PsiSize { get; } 33 | public uint MainThread { get; } 34 | public byte[] BoardId { get; } 35 | public byte[] BootLine { get; } 36 | private readonly byte[] _data; 37 | private readonly int _offset; 38 | private readonly int _length; 39 | 40 | public NVRAM(ReadOnlySpan data, uint offset = NvRamOffset, uint length = NvRamLength) 41 | { 42 | _data = new byte[data.Length]; 43 | data.CopyTo(_data.AsSpan()); 44 | 45 | _offset = (int)offset; 46 | _length = (int)length; 47 | 48 | Version = GetUint(0); 49 | 50 | BootLine = _data[OffsetOf(0x4)..OffsetOf(0x104)]; 51 | BoardId = _data[OffsetOf(0x104)..OffsetOf(0x114)]; 52 | MainThread = GetUint(0x114); 53 | PsiSize = GetUint(0x118); 54 | NumMacAddr = GetUint(0x11C); 55 | BaseMacAddr = _data[OffsetOf(0x120)..OffsetOf(0x126)]; 56 | OldCheckSum = GetUint(0x128); 57 | GponVendorId = _data[OffsetOf(0x12C)..OffsetOf(0x130)]; 58 | GponVendorSerialNumber = _data[OffsetOf(0x130)..OffsetOf(0x139)]; 59 | GponPassword = Encoding.UTF8.GetString(_data[OffsetOf(0x139)..OffsetOf(0x144)]); 60 | WpsDevPin = _data[OffsetOf(0x144)..OffsetOf(0x14C)]; 61 | WLanParams = _data[OffsetOf(0x14C)..OffsetOf(0x24C)]; 62 | SyslogSize = GetUint(0x24C); 63 | NandPartOfsKb = GetUint(0x250); 64 | NandPartSizeKb = GetUint(0x264); 65 | VoiceBoardId = _data[OffsetOf(0x278)..OffsetOf(0x288)]; 66 | AfeId = _data[OffsetOf(0x288)..OffsetOf(0x290)]; 67 | 68 | Checksum = GetUint(NvRamCrcOffset); 69 | 70 | var crcIndex = _offset + NvRamCrcOffset; 71 | _data[crcIndex++] = 0; 72 | _data[crcIndex++] = 0; 73 | _data[crcIndex++] = 0; 74 | _data[crcIndex] = 0; 75 | 76 | var crc = CRC32.GenerateCrc(_data.AsSpan(_offset, _length)); 77 | 78 | if (crc != Checksum) 79 | { 80 | throw new InvalidOperationException("Invalid data, CRC doesn't match"); 81 | } 82 | } 83 | 84 | public void SetBaseMacAddress(string mac) 85 | { 86 | var data = AsBytes(mac); 87 | 88 | SetBaseMacAddress(data); 89 | } 90 | 91 | public void SetBaseMacAddress(ReadOnlySpan mac) 92 | { 93 | const int MacRelativeOffset = 0x120; 94 | const int MacLength = 6; 95 | 96 | if (mac.Length != MacLength) 97 | { 98 | throw new ArgumentOutOfRangeException(nameof(mac)); 99 | } 100 | 101 | BaseMacAddr = SetBytes(mac, MacRelativeOffset, MacLength, false); 102 | } 103 | 104 | public void SetGponId(string id) 105 | { 106 | SetGponId(Encoding.UTF8.GetBytes(id)); 107 | } 108 | 109 | public void SetGponId(ReadOnlySpan id) 110 | { 111 | const int VendorIdRelativeOffset = 0x12C; 112 | const int VendorIdLength = 4; 113 | 114 | if (id.Length != VendorIdLength) 115 | { 116 | throw new ArgumentOutOfRangeException(nameof(id)); 117 | } 118 | 119 | GponVendorId = SetBytes(id, VendorIdRelativeOffset, VendorIdLength); 120 | } 121 | 122 | public void SetGponSerialNumber(string serialNumber) 123 | { 124 | if (_snMatcher.IsMatch(serialNumber)) 125 | { 126 | this.SetGponId(AsBytes(serialNumber.Replace("-", "")[0..8])); 127 | SetGponSerialNumber(Encoding.UTF8.GetBytes(serialNumber.Replace("-", "")[8..])); 128 | } 129 | else 130 | { 131 | if (serialNumber.Contains("-")) throw new InvalidOperationException($"Invalid serial number: {serialNumber}."); 132 | SetGponSerialNumber(Encoding.UTF8.GetBytes(serialNumber)); 133 | } 134 | } 135 | 136 | public void SetGponSerialNumber(ReadOnlySpan serialNumber) 137 | { 138 | const int VendorSnRelativeOffset = 0x130; 139 | const int VendorSnLength = 8; 140 | 141 | if (serialNumber.Length != VendorSnLength) 142 | { 143 | throw new ArgumentOutOfRangeException(nameof(serialNumber)); 144 | } 145 | 146 | GponVendorSerialNumber = SetBytes(serialNumber, VendorSnRelativeOffset, VendorSnLength); 147 | } 148 | 149 | public void SetGponPassword(string password) 150 | { 151 | const int PasswordOffset = 0x139; 152 | const int MaxPasswordLength = 10; 153 | 154 | if (password == null) 155 | { 156 | throw new ArgumentNullException(nameof(password)); 157 | } 158 | 159 | if (password.Length > MaxPasswordLength) 160 | { 161 | throw new ArgumentOutOfRangeException(nameof(password)); 162 | } 163 | 164 | byte[] bits = default!; 165 | 166 | if (_pwMatcher.IsMatch(password)) 167 | { 168 | password = password.Replace("-", "").PadLeft(MaxPasswordLength, '0'); 169 | bits = AsBytes(password); 170 | } 171 | else 172 | { 173 | password = password.PadLeft(MaxPasswordLength, '0'); 174 | bits = Encoding.UTF8.GetBytes(password); 175 | } 176 | 177 | SetBytes(bits.AsSpan(), PasswordOffset, password.Length); 178 | 179 | GponPassword = password; 180 | } 181 | 182 | public byte[] CompletePatch() 183 | { 184 | var bits = _data.AsSpan(_offset, _length); 185 | 186 | Checksum = CRC32.GenerateCrc(bits); 187 | 188 | var bitsIndex = NvRamCrcOffset; 189 | bits[bitsIndex++] = (byte)(Checksum >> 24); 190 | bits[bitsIndex++] = (byte)((Checksum >> 16) & 0xFF); 191 | bits[bitsIndex++] = (byte)((Checksum >> 8) & 0xFF); 192 | bits[bitsIndex] = (byte)(Checksum & 0xFF); 193 | 194 | return _data; 195 | } 196 | 197 | public override string ToString() 198 | { 199 | var sb = new StringBuilder(); 200 | sb.AppendLine("--- NVRAM Information --"); 201 | sb.AppendLine($"- mtdblock3 hash: {ComputeSha256Hash(this._data)}"); 202 | sb.AppendLine($"- NVRAM Version: {this.Version}"); 203 | sb.AppendLine($"- Boot parameters: {UnsafeAsciiBytesToString(this.BootLine)}"); 204 | sb.AppendLine($"- Board Id: {UnsafeAsciiBytesToString(this.BoardId)}"); 205 | sb.AppendLine($"- PSI size: {this.PsiSize}"); 206 | sb.AppendLine($"- Total MAC addresses: {this.NumMacAddr}"); 207 | sb.AppendLine($"- GPON MAC address: { BitConverter.ToString(this.BaseMacAddr).Replace("-", ":")}"); 208 | sb.AppendLine($"- GPON Vendor Id: {Encoding.UTF8.GetString(this.GponVendorId)}"); 209 | sb.AppendLine($"- GPON Serial Number: {UnsafeAsciiBytesToString(this.GponVendorSerialNumber)}"); 210 | sb.AppendLine($"- GPON SLID (password): {this.GponPassword.TrimEnd((char)0)}"); 211 | sb.AppendLine($"- Checksum: {this.Checksum}"); 212 | return sb.ToString(); 213 | } 214 | 215 | public static string UnsafeAsciiBytesToString(byte[] buffer) 216 | { 217 | unsafe 218 | { 219 | fixed (byte* pAscii = buffer) 220 | { 221 | return new String((sbyte*)pAscii); 222 | } 223 | } 224 | } 225 | 226 | private int OffsetOf(int value) => _offset + value; 227 | private int OffsetOf(int value1, int value2) => _offset + value1 + value2; 228 | 229 | private byte[] SetBytes(ReadOnlySpan source, int relativeOffset, int length, bool zeroTerminate = true) 230 | { 231 | var dataIndex = _offset + relativeOffset; 232 | var dataEnd = dataIndex + length; 233 | var sourceIndex = 0; 234 | 235 | while (dataIndex < dataEnd) 236 | { 237 | _data[dataIndex++] = source[sourceIndex++]; 238 | } 239 | 240 | if (zeroTerminate) 241 | { 242 | _data[dataIndex] = 0; 243 | } 244 | 245 | return _data[OffsetOf(relativeOffset)..OffsetOf(relativeOffset, length)]; 246 | } 247 | 248 | private static byte[] AsBytes(string data) 249 | { 250 | if (data == null) 251 | { 252 | throw new ArgumentNullException(nameof(data)); 253 | } 254 | 255 | if (data.Length % 2 != 0) 256 | { 257 | throw new ArgumentException("Data must be an even length.", nameof(data)); 258 | } 259 | 260 | data = data.ToLower(); 261 | 262 | var len = data.Length / 2; 263 | 264 | var bits = new byte[len]; 265 | 266 | var bitsIndex = 0; 267 | var dataIndex = 0; 268 | 269 | while (dataIndex < data.Length) 270 | { 271 | var highNibble = FromHex(data[dataIndex++]); 272 | var lowNibble = FromHex(data[dataIndex++]); 273 | bits[bitsIndex++] = (byte)(highNibble << 4 | lowNibble); 274 | } 275 | 276 | return bits; 277 | 278 | static int FromHex(char c) => 279 | c switch 280 | { 281 | >= 'a' and <= 'f' => 10 + (c - 'a'), 282 | >= '0' and <= '9' => c - '0', 283 | _ => throw new ArgumentOutOfRangeException(nameof(c)) 284 | }; 285 | } 286 | 287 | private static string ComputeSha256Hash(byte[] rawData) 288 | { 289 | using (SHA256 sha256Hash = SHA256.Create()) 290 | { 291 | byte[] bytes = sha256Hash.ComputeHash(rawData); 292 | 293 | StringBuilder builder = new StringBuilder(); 294 | for (int i = 0; i < bytes.Length; i++) 295 | { 296 | builder.Append(bytes[i].ToString("x2")); 297 | } 298 | return builder.ToString(); 299 | } 300 | } 301 | 302 | private uint GetUint(int offset) 303 | { 304 | var bits = _data.AsSpan(OffsetOf(offset), 4); 305 | 306 | return (uint)(bits[0] << 24 | 307 | bits[1] << 16 | 308 | bits[2] << 8 | 309 | bits[3]); 310 | } 311 | } 312 | } -------------------------------------------------------------------------------- /src/UFiber.Configurator/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using Renci.SshNet; 4 | using UFiber.Configurator; 5 | using System.CommandLine; 6 | using System.CommandLine.Invocation; 7 | 8 | var rootCommand = new RootCommand("Apply configuration changes to UFiber devices") 9 | { 10 | new Option( 11 | "--host", 12 | getDefaultValue: () => "192.168.1.1", 13 | "IP or hostname of the target UFiber device."), 14 | new Option( 15 | "--user", 16 | getDefaultValue: () => "ubnt", 17 | "SSH user name."), 18 | new Option( 19 | "--pw", 20 | getDefaultValue: () => "ubnt", 21 | "SSH password."), 22 | new Option( 23 | "--port", 24 | getDefaultValue: () => 22, 25 | "SSH port of the target UFiber device."), 26 | new Option( 27 | "--dry-run", 28 | "Don't apply the patched file to the target UFiber device. (i.e. dry-run)"), 29 | new Option( 30 | "--slid", 31 | "The SLID (or PLOAM Password).", ArgumentArity.ZeroOrOne), 32 | new Option( 33 | "--vendor", 34 | "4-digit Vendor Id (e.g. HWTC, MTSC, etc.). Combined with --serial, a GPON Serial Number is built.", ArgumentArity.ZeroOrOne), 35 | new Option( 36 | "--serial", 37 | "8-digit (e.g. 01234567) serial number or 16-digit (e.g. 41-4C-43-4C-xx-xx-xx-xx) HEX serial number. Combined with --vendor, a GPON Serial Number is built. Note: If a 16-digit HEX value is provided, the first 4 bytes (8 digits) will replace whatever value was passed to Vendor Id with '--vendor'.", ArgumentArity.ZeroOrOne), 38 | new Option( 39 | "--mac", 40 | "The desired MAC address to clone.", ArgumentArity.ZeroOrOne), 41 | new Option( 42 | "--restore", 43 | "Restore a previous version of the firmware.", ArgumentArity.ZeroOrOne) 44 | }; 45 | 46 | SshClient GetSSHClient(string userName, string password, string host, int port = 22) 47 | { 48 | var client = new SshClient(host, port, userName, password); 49 | client.Connect(); 50 | return client; 51 | } 52 | 53 | ScpClient GetSCPClient(string userName, string password, string host, int port = 22) 54 | { 55 | var client = new ScpClient(host, port, userName, password); 56 | client.Connect(); 57 | return client; 58 | } 59 | 60 | rootCommand.Handler = CommandHandler 61 | .Create( 62 | (host, user, pw, port, dryRun, slid, vendor, serial, mac, fwToRestore) => 63 | { 64 | if (string.IsNullOrWhiteSpace(host)) 65 | { 66 | Console.Error.WriteLine("Host is a required parameter and can't be empty."); 67 | Environment.ExitCode = -1; 68 | return; 69 | } 70 | 71 | SshClient ssh = default!; 72 | ScpClient scp = default!; 73 | 74 | try 75 | { 76 | // Connect to SSH and SCP 77 | ssh = GetSSHClient(user, pw, host, port); 78 | scp = GetSCPClient(user, pw, host, port); 79 | } 80 | catch (Exception ex) 81 | { 82 | Console.Error.WriteLine($"Unable to connect to the target UFiber device. Please check the connection parameters and try again. Error: {ex.Message}"); 83 | Environment.ExitCode = -1; 84 | return; 85 | } 86 | 87 | var imgName = $"fw-{DateTime.UtcNow.ToString("ddMMyyyy-hhmmss")}.bin"; 88 | 89 | // Dump the image file 90 | var cmd = ssh.RunCommand($"cat /dev/mtdblock3 > /tmp/{imgName}"); 91 | if (cmd.ExitStatus != 0) 92 | { 93 | Console.Error.WriteLine($"Failute to dump the image file. Error: {cmd.Error}"); 94 | Environment.ExitCode = cmd.ExitStatus; 95 | return; 96 | } 97 | 98 | const string localDumps = "./dumps"; 99 | 100 | if (!Directory.Exists(localDumps)) 101 | { 102 | Directory.CreateDirectory(localDumps); 103 | } 104 | 105 | // Download the dump 106 | try 107 | { 108 | scp.Download($"/tmp/{imgName}", new DirectoryInfo(localDumps)); 109 | ssh.RunCommand($"rm /tmp/{imgName}"); 110 | } 111 | catch (Exception ex) 112 | { 113 | Console.Error.WriteLine($"Failure downloading original image file from the UFiber device. Error: {ex.Message}."); 114 | Environment.ExitCode = -1; 115 | return; 116 | } 117 | 118 | if (!string.IsNullOrWhiteSpace(fwToRestore)) 119 | { 120 | const string targetFileToRestore = "/tmp/restore.bin"; 121 | Console.WriteLine("Uploading original file to the target UFiber device..."); 122 | try 123 | { 124 | scp.Upload(new FileInfo(fwToRestore), targetFileToRestore); 125 | } 126 | catch (Exception ex) 127 | { 128 | Console.Error.WriteLine($"Failure uploading original image file to the UFiber device. Error: {ex.Message}."); 129 | Environment.ExitCode = -1; 130 | return; 131 | } 132 | Console.WriteLine("Uploaded!"); 133 | Console.WriteLine("### Applying original file on the target UFiber device..."); 134 | cmd = ssh.RunCommand($"dd if={targetFileToRestore} of=/dev/mtdblock3 && rm {targetFileToRestore}"); 135 | if (cmd.ExitStatus != 0) 136 | { 137 | Console.Error.WriteLine($"Failure to apply original image file. Error: {cmd.Error}"); 138 | Environment.ExitCode = cmd.ExitStatus; 139 | return; 140 | } 141 | Console.WriteLine("### Applied patch! Please reboot your UFiber device to load the new image."); 142 | return; 143 | } 144 | 145 | var ram = new NVRAM(File.ReadAllBytes(Path.Combine(localDumps, imgName))); 146 | Console.WriteLine("### Original Image ###"); 147 | Console.WriteLine(ram); 148 | 149 | Console.WriteLine($"### Patching {imgName}..."); 150 | 151 | if (!string.IsNullOrWhiteSpace(vendor) && string.IsNullOrWhiteSpace(serial)) 152 | { 153 | Console.Error.WriteLine($"To set the GPON Serial Number, you must pass both --vendor and --serial. You can skip the --vendor if you provide the full serial as HEX to the --serial."); 154 | Environment.ExitCode = -1; 155 | return; 156 | } 157 | else if (!string.IsNullOrWhiteSpace(vendor) && !string.IsNullOrWhiteSpace(serial)) 158 | { 159 | ram.SetGponId(vendor); 160 | ram.SetGponSerialNumber(serial); 161 | } 162 | else if (string.IsNullOrWhiteSpace(vendor) && !string.IsNullOrWhiteSpace(serial)) 163 | { 164 | ram.SetGponSerialNumber(serial); 165 | } 166 | 167 | if (!string.IsNullOrWhiteSpace(mac)) 168 | { 169 | ram.SetBaseMacAddress(mac); 170 | } 171 | 172 | if (!string.IsNullOrWhiteSpace(slid)) 173 | { 174 | ram.SetGponPassword(slid); 175 | } 176 | 177 | var patched = ram.CompletePatch(); 178 | 179 | const string localPatched = "./patched"; 180 | 181 | if (!Directory.Exists(localPatched)) 182 | { 183 | Directory.CreateDirectory(localPatched); 184 | } 185 | 186 | var patchedFileName = $"patched-{imgName}"; 187 | File.WriteAllBytes(Path.Combine(localPatched, patchedFileName), patched); 188 | Console.WriteLine($"### Patched {imgName}!"); 189 | Console.WriteLine(ram); 190 | 191 | if (!dryRun) 192 | { 193 | Console.WriteLine("Uploading patched file to the target UFiber device..."); 194 | try 195 | { 196 | scp.Upload(new FileInfo(Path.Combine(localPatched, patchedFileName)), $"/tmp/{patchedFileName}"); 197 | } 198 | catch (Exception ex) 199 | { 200 | Console.Error.WriteLine($"Failure uploading patched image file to the UFiber device. Error: {ex.Message}."); 201 | Environment.ExitCode = -1; 202 | return; 203 | } 204 | Console.WriteLine("Uploaded!"); 205 | Console.WriteLine("### Applying patched file on the target UFiber device..."); 206 | cmd = ssh.RunCommand($"dd if=/tmp/{patchedFileName} of=/dev/mtdblock3 && rm /tmp/{patchedFileName}"); 207 | if (cmd.ExitStatus != 0) 208 | { 209 | Console.Error.WriteLine($"Failure to apply patched image file. Error: {cmd.Error}"); 210 | Environment.ExitCode = cmd.ExitStatus; 211 | return; 212 | } 213 | Console.WriteLine("### Applied patch! Please reboot your UFiber device to load the new image."); 214 | } 215 | else 216 | { 217 | Console.WriteLine($"### Dry-run completed. The patched file can be found at '{Path.Combine(localDumps, patchedFileName)}'."); 218 | } 219 | }); 220 | 221 | return rootCommand.Invoke(args); 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | -------------------------------------------------------------------------------- /src/UFiber.Configurator/UFiber.Configurator.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | enable 7 | true 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | --------------------------------------------------------------------------------